theNeighbourhoodGhost theNeighbourhoodGhost - 2 months ago 6
Javascript Question

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]]

Answer

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
Comments