reduce() method
Using reduce() method to find the sum of all even numbers in an array

const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const evenSum = numbers.reduce((acc, curr) => {
if (curr % 2 === 0) {
return acc + curr;
} else {
return acc;
}
}, 0);
console.log(evenSum); // Output: 30
In this code snippet, the reduce()
method is used to iterate through the numbers
array and keep track of the sum of all even numbers using the accumulator (acc
) variable. The curr
parameter represents the current element being processed in the array.
Inside the reducer function, an if
statement checks if the current number is even by using the modulo operator (%
). If it is even, the current number is added to the accumulator (acc
). Otherwise, the accumulator is returned as is.
The reduce()
method takes an optional initial value, which is set to 0
in this case. This initial value is used as the starting value for the accumulator.
This code snippet is useful because it demonstrates how to use the reduce()
method to perform a specific task on an array in a concise and efficient manner.