gnarois
gnarois

Reputation: 339

Sum the negative numbers of an array using reduce() in JavaScript

I'm trying to build a function that sums the negative numbers of a given array. I want to use the reduce() function here. This seems like a dead simple exercise. Using a ternary operator to check if number is negative and therefore to sum it to the total. However, result is not as I hoped:

const reducer = (tot, num) => ((num < 0) ? tot + num : tot);
const sumOfNegative = numbers => numbers.reduce(reducer);

console.log(sumOfNegative([3, -1, 0]))
// => 2

Expected to get -1 here. Not sure I have a good grasp at what reduce() is doing each step. What am I doing wrong and how is the code iterating through the array?

Upvotes: 1

Views: 3106

Answers (1)

trincot
trincot

Reputation: 350365

If you don't provide a second argument to .reduce, then it will take the first array value as the start of the accumulation (tot), meaning that the first element of your array will not be checked for being negative.

Solution: provide the second argument: make it 0. This also means you no longer need the ternary operator:

const sumOfNegative = numbers => numbers.reduce(reducer, 0);

Upvotes: 5

Related Questions