0

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?

2
  • [[], [], [], []].reduce((x, y) => x.length + y.length) is not working because you are returning an integer value and not an array. So in second iteration, it will fail as number does not have .length Commented Oct 31, 2017 at 10:56
  • please add the potential result of the operation. Commented Oct 31, 2017 at 10:57

3 Answers 3

2

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
Sign up to request clarification or add additional context in comments.

3 Comments

This is the correct answer, it just looks like you missed the callback structure for reduce. For future reference the MDN page for the .reduce is pretty comprehensive
ohhhh I see. so 'array' in this case is the element for the current iteration?
Yes - exactly. reduce is a bit of a weird one as the first argument to the callback is the accumulator.
1

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

Comments

1

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

Comments

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.