mangokitty
mangokitty

Reputation: 2399

Find average of each array within an array

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.

Upvotes: 1

Views: 64

Answers (2)

Nina Scholz
Nina Scholz

Reputation: 386766

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

Upvotes: 5

Avocado
Avocado

Reputation: 901

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

Upvotes: 1

Related Questions