Reputation: 625
I am trying to figure out how can I reduce something like [[1,2,3],[1,2],[]]
to the sum of entries of array. I want to recieve the total number of elements in nested arrays, so the answer to this question would be 5
. I don't care about what is in those arrays, just their lengths.
Thanks so much for support!
Upvotes: 1
Views: 61
Reputation: 28196
Tareq's solution is fine for the example given.
But if you have an array with deeper nesting and possible empty subarrays in it, then the following will help:
var a=[[],[1,2,3],[1,2],[],[[4,[5,,,6]]],[]];
console.log(a.toString().replace(/^,|,+(?=,|$)/g,'').split(',').length);
This is probably getting a little silly, but now the expression will ignore any empty elements, wherever they might pop up. The regular expression checks for single commas at the beginning, mutliple commas in the middle and single commas at the end of the string and removes them accordingly.
Upvotes: 1