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. Commented Dec 11, 2015 at 15:13
  • 3
    The concept you're after is called "flattening" the array. Commented Dec 11, 2015 at 15:13

3 Answers 3

8

There is no need to loop

arrayX = [].concat.apply([], arrayX);
Sign up to request clarification or add additional context in comments.

2 Comments

it works only if the array is not nested.
@NinaScholz Works fine for OPs case. I love when people add new requirements that do not matter in the OPs case.
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

Comments

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 Comments

Was my answer wrong?
you seem happy , no one here likes that in my exp, avoid 'fan' , 'excelent', 'super' keywords

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.