0

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?

5
  • You are confusing the comma operator that returns the array... Commented Oct 9, 2020 at 19:44
  • Why are you converting a boolean to a number? [+(boolean expression)] doesn't make sense Commented Oct 9, 2020 at 19:44
  • @Taplar, otherwise you need an object with true and false keys. Commented Oct 9, 2020 at 19:45
  • Why have that at all? The mod is already going to return 0 or 1. @NinaScholz Commented Oct 9, 2020 at 19:46
  • @Taplar, it's not my code. Commented Oct 9, 2020 at 19:46

2 Answers 2

3

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)

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

Comments

0

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

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.