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
Release: 2024-12-17 09:46:26
Original
421 people have browsed it

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
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template