1

I'm trying to write a map/reduce to get the average of each array within an array.

For example.

[[1][2,3][4,5,6,7]] => [1, 2.5, 5.5] 

Right now this is my code where result is the array of arrays:

result.map(array => {
  return array.reduce((a, b) => (a + b)) / array.length;
})

const result = [
  [1],
  [2, 3],
  [4, 5, 6, 7]
]

console.log(result.map(array => {
  return array.reduce((a, b) => (a + b)) / array.length;
}))

Any help to get the desired output is much appreciated. As it stands, my output is reducing to an array of NaN's instead of the averages.

1
  • 3
    With the syntax corrected your code works. The problem is somewhere else. For example the result array contains non numbers. Commented Oct 30, 2019 at 17:56

2 Answers 2

5

You need a closing parentesis.

By using Array#reduce with arrays with unknown length, you need to take a start value, which is in this case of a length of zero the result.

var result = [[1], [2, 3], [4, 5, 6, 7]],
    avg = result.map(array => array.reduce((a, b) => a + b, 0) / array.length);
    //                                                    ^^^                ^
    //                                                    optional           required

console.log(avg);

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

1 Comment

Not really [1].reduce((a, b) => a + b) The problem would be for empty arrays.
1

you must provide a second argument to the reduce function, the initial value of a. So:

result.map(array => {
  return array.reduce((a, b) => a + b, 0) / array.length;
});

You may also want to ensure that array.length > 0 before you divide by it

1 Comment

OP's code works fine without the the initialValue argument as well

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.