简体   繁体   中英

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

尝试扁平化

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

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

 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); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM