Voldy21
Voldy21

Reputation: 39

Two initial values for reduce array method?

const result = [1,2,3,4,5].reduce((acc,cur) => (acc[+(cur % 2 !== 0)] += cur, acc),  [0, 0])

console.log(result)

It is supposed to sum up the even values and the odd values in the array but how can we have 2 different initializers for the initial values? There are 2 commas at the end of the reduce method, how do they work in this case?

Upvotes: 0

Views: 187

Answers (2)

epascarello
epascarello

Reputation: 207557

You are confusing the comma operator in the function. Below it is written without the fat arrow syntax with the implicit return.

var res = [1, 2, 3, 4, 5].reduce(function(acc, cur) {
  acc[+(cur % 2 !== 0)] += cur;
  return acc
}, [0, 0]);

console.log(res)

Upvotes: 3

Nina Scholz
Nina Scholz

Reputation: 386883

In reality, you have only one start value for the accumulator, an array.

[1, 2, 3, 4, 5].reduce(
    (acc, cur) => (acc[+(cur % 2 !== 0)] += cur, acc),
    [0, 0]
)

Upvotes: 0

Related Questions