Home > Web Front-end > JS Tutorial > How Can JavaScript's `reduce` Method Efficiently Sum Array Elements?

How Can JavaScript's `reduce` Method Efficiently Sum Array Elements?

DDD
Release: 2024-12-15 11:54:12
Original
216 people have browsed it

How Can JavaScript's `reduce` Method Efficiently Sum Array Elements?

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

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:

  • partialSum: The accumulator, which initially holds the initial value (0) and is updated with each iteration to contain the running sum.
  • a: The current element of the array being iterated over.

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template