Dimitry Ivashchuk
Dimitry Ivashchuk

Reputation: 625

Reducing an array of arrays

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

Answers (2)

Carsten Massmann
Carsten Massmann

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

Tareq
Tareq

Reputation: 5363

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

Upvotes: 5

Related Questions