Reputation:
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
Reputation: 36609
Array#reduce
could be used but [at your own risk]
Use Array.isArray
to determine whether the passed value is an Array
.
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
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
Reputation: 2089
try flatting it
[].concat.apply([], [1, [4, 5, 2, 1], 2, [4, 5, 2, 6], 2, [3, 3]]).length
Upvotes: 2