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.

  • Create an array and add all the elements to it, by traversing the original array using [for](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/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 '15 at 15:13
  • 3
    The concept you're after is called "flattening" the array. – user229044 Dec 11 '15 at 15:13

3 Answers3

8

There is no need to loop

arrayX = [].concat.apply([], arrayX);
epascarello
  • 204,599
  • 20
  • 195
  • 236
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

bcr
  • 3,791
  • 18
  • 28
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();
Andrew Bone
  • 7,092
  • 2
  • 18
  • 33