Summation of Array Elements
Given an array containing numerical values, determining their aggregate sum is a common programming task. Let's examine an array like [1, 2, 3, 4] and explore how to compute its sum.
Using Reduce
In modern JavaScript, the reduce method is an ideal tool for this task. It allows us to iteratively combine array elements into a single value. Here's how we can leverage reduce in ECMAScript 2015 or later:
const sum = [1, 2, 3].reduce((partialSum, a) => partialSum + a, 0); console.log(sum); // 6
In this example, the reduce method takes two parameters: a callback function and an initial value (0 in this case).
The callback function receives two arguments:
The callback function returns the updated partialSum value for each element, and the final value of partialSum is assigned to the sum variable.
The above is the detailed content of How Can JavaScript's `reduce` Method Efficiently Sum Array Elements?. For more information, please follow other related articles on the PHP Chinese website!