Reduce() method not working - help

Hello all, another newbie question for you.

I have written the code below trying to practice with iterators methods and chaining methods.

With the code below I wanted to have the sum of all elements > 50 from the Array numbers

It seems that the code only displays the first element > 50 and not a sum as reduce() should process.

const numbers = [1, 24, 30, 7, 122, 587, 1022, 74]

const newSum = numbers.filter(newSum => newSum > 50)

.reduce(total => total)

console.log(newSum)

I am not sure what is I do wrong?

The issue is in the reduce function, which should take two parameters: the “accumulator” (usually named total) and the current value from the array. The function should return the result of adding the accumulator to the current value. You are passing only one parameter to the reduce function and not performing any addition operation.

Below, I will provide two examples, one with if/else (simpler) and another with filter/reduce.

const numbers = [1, 24, 30, 7, 122, 587, 1022, 74];

const newSum = numbers.reduce((total, current) => {
  if (current > 50) {
    return total + current;
  } else {
    return total;
  }
}, 0);

console.log(newSum);
const numbers = [1, 24, 30, 7, 122, 587, 1022, 74];

const newSum = numbers
  .filter(number => number > 50) // Filters out numbers greater than 50
  .reduce((total, current) => total + current, 0); // Adds up the filtered values, starting from 0

console.log(newSum); // This should now display the sum of the numbers greater than 50
2 Likes

Thank you! I totally bypassed the information about the two mandatory parameters.

Are the names of the two parameters at the coder’s discretion or is there a convention for using total and current?

The parameter names in the reduce function are entirely up to you and don’t need to follow a specific convention, but it’s good practice to choose names that clearly describe what each parameter represents.

The first parameter is usually called accumulator (or total, sum, etc.), because it accumulates the result of the operation being performed on each element of the array. The second parameter is generally called currentValue (or current, item, etc.), as it represents the current value being processed in the array.

1 Like