1

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!

2 Answers 2

5

You can use reduce as one possible solution.

let data = [[1,2,3],[1,2],[]];

const total = data.reduce((acc, entry) => acc += entry.length ,0);

console.log('total ' , total);

Sign up to request clarification or add additional context in comments.

1 Comment

@DimitryIvashchuk, remember, If this was useful to you, please upvote this question for future readers and consider accepting it as correct.
1

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.

3 Comments

so does replace.(/,,+/,',') make the array a into a one dimensional array separated by comas?
.toString() turns the array into a comma separated list and thereby reduces the array to a single depth level. The replace () removes double commas in the string which otherwise would increase the length of the one-level array generated by split(). The solution is still not perfect, as it will not remove leading or trailing commas ...
Leading and trailing commas are now also taken care of, so, this should work for all conceivable types of arrays of arrays.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.