2
var arrayX = [ ["fire", "lightning"], [3, "ice"], [85], ["wind", "earth", 0] ];

In the example above, arrayX consists of four elements, each of which is also an array. As it stands now, arrayX.length equals 4.

I wonder if it is possible to remove all the four pairs of square brackets inside, leaving only the most outer bracket, so that the computer can now count the total number of all the individual elements in arrayX. I mean, like this:

var arrayX = ["fire", "lightning", 3, "ice", 85, "wind", "earth", 0];

Now, arrayX.length returns 8, and this is the number I want to get. I started to learn programming just several days ago, so I'm not sure how to go about this. Thank you in advance.

2
  • Create an array and add all the elements to it, by traversing the original array using for loop, or use arrayX.join().split(',') but here all the values are converted to string, but length will be 8, as per the question.
    – rajuGT
    Dec 11, 2015 at 15:13
  • 3
    The concept you're after is called "flattening" the array.
    – user229044
    Dec 11, 2015 at 15:13

3 Answers 3

8

There is no need to loop

arrayX = [].concat.apply([], arrayX);
2
  • it works only if the array is not nested. Dec 11, 2015 at 15:29
  • 1
    @NinaScholz Works fine for OPs case. I love when people add new requirements that do not matter in the OPs case. Dec 11, 2015 at 15:34
1

Use Array.prototype.reduce():

var flattened = [ ["fire", "lightning"], [3, "ice"], [85], ["wind", "earth", 0] ].reduce(function(a, b) {
  return a.concat(b);
}, []);

docs here

0

I'm a fan of the concat method myself

function concatArray() {
  var arrayX = [
    ["fire", "lightning"],
    [3, "ice"],
    [85],
    ["wind", "earth", 0]
  ];
  arrayX = [].concat.apply([], arrayX);
  console.log(arrayX.length);
}

concatArray();

2
  • Was my answer wrong? Dec 12, 2015 at 18:20
  • you seem happy , no one here likes that in my exp, avoid 'fan' , 'excelent', 'super' keywords
    – arnoldssss
    Feb 9, 2019 at 0:37

Not the answer you're looking for? Browse other questions tagged or ask your own question.