Home >Web Front-end >JS Tutorial >How to Efficiently Sum an Array of Numbers using Reduce?

How to Efficiently Sum an Array of Numbers using Reduce?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-17 09:46:26422browse

How to Efficiently Sum an Array of Numbers using Reduce?

How to Sum an Array of Numbers using Reduce

Finding the sum of an array's elements is a common task. One intuitive approach might be using $.each. However, a more specialized solution is available using the reduce function.

Using Reduce

Reduce takes a callback function that combines successive elements into a single result. In our case, we can define a callback to add each element to the sum. The initial value (0) is included as the second argument to reduce.

For ECMAScript 2015:

const sum = [1, 2, 3].reduce((partialSum, a) => partialSum + a, 0);
console.log(sum); // 6

The reduce function iterates through the array, applying the callback to each element and the partial sum value. The resulting sum is returned. This method is efficient and concise for finding array sums.

The above is the detailed content of How to Efficiently Sum an Array of Numbers using Reduce?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn