JavaScript Array reduce
Method (Live Playground)
The reduce
method in JavaScript applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value.
Here's an example:
let numbers = [1, 2, 3, 4, 5];
let sum = numbers.reduce(function (total, number) {
return total + number;
}, 0);
console.log(sum);
// Expected output: 15
In this example, numbers.reduce(function(total, number) { return total + number; }, 0)
returns the sum of all elements in the numbers
array. The number 0
passed as the second argument to reduce
is the initial value for the total
.
The reduce
method does not change the original array. For example, if we console.log the numbers
array, we will see that it stays the same:
console.log(numbers);
// Expected output: [1, 2, 3, 4, 5]
The reduce
method is useful when you need to process an array's elements into a single value, such as summing numbers or finding a product.
Always practice the reduce
method with different scenarios to improve your understanding!