user6885321
user6885321

Reputation:

Find the length of an Array consisting of 2D arrays

Is there a way to find the length of this array, and all the sub arrays inside it. Meaning 13 and not 6? Without having to use loops and adding up all the elements inside the arrays.

I'm looking for one command that can do this.

[1, [4, 5, 2, 1], 2, [4, 5, 2, 6], 2, [3, 3]]

Upvotes: 1

Views: 46

Answers (3)

Rayon
Rayon

Reputation: 36609

var input = [1, [4, 5, 2, 1], 2, [4, 5, 2, 6], 2, [3, 3]];
var length = input.reduce(function(a, b) {
  return a + (Array.isArray(b) ? b.length : 1);
}, 0);
console.log(length);

Upvotes: 1

adeneo
adeneo

Reputation: 318162

A bit of a hack, but you can do

arr.toString().split(',').length

join(',') would work as well, it flattens everything

var arr = [1, [4, 5, 2, 1], 2, [4, 5, 2, 6], 2, [3, 3]];

console.log(arr.toString().split(',').length)

if all you wanted was the number of indices in total


If the array contains commas inside the indices, those could be removed for the same effect

JSON.stringify(arr).replace(/"(.*?)"/g,'1').split(',').length

Upvotes: 1

naortor
naortor

Reputation: 2089

try flatting it

[].concat.apply([], [1, [4, 5, 2, 1], 2, [4, 5, 2, 6], 2, [3, 3]]).length

Upvotes: 2

Related Questions