简体   繁体   中英

Reduce array of empty arrays

I'm trying to run a reduce function on an array on arrays. The arrays inside the array can be empty. So: [[], [], [], []].reduce((x, y) => x.length + y.length) does not work

[[2, 3], [2, 3], [3, 5], [5, 6]].reduce((x, y) => x.length + y.length) doesn't seem to work either?

Am I missing something?

The signature for the function you pass as the first argument to .reduce is

(accumulator, currentValue, currentIndex, array) => {...}

The second argument you can pass to reduce is the starting value for the accumulator.

In your case, (x, y) => x.length + y.length is trying to get the length of the accumulator, named x , which will be undefined , and add it to the length of the first array in the parent array.

When you try to add undefined to a number, you get NaN .

My guess is that you're trying to calculate the aggregate length of all the arrays in your parent array? If so, try this...

[[],[],[],[]].reduce((acc, array) => acc + array.length, 0)
// returns 0

[[2, 3], [2, 3], [3, 5], [5, 6]].reduce((acc, array) => acc + array.length, 0)
// returns 8

You could take a start value for Array#reduce .

 var getLength = (r, x) => r + x.length, length0 = [[], [], [], []].reduce(getLength, 0), // ^ length1 = [[2, 3], [2, 3], [3, 5], [5, 6]].reduce(getLength, 0); // ^ console.log(length0); console.log(length1); 

Watch out because x.length and y.length will eventually turn into integers and integers don't have a length property.

You can do something like

(x, y) => x.length || x + y.length || y

So that if x.length exists, it gets used, otherwise just use the value of x

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