Reduce() Array Method in Javascript

The reduce() method is a higher-order function available in JavaScript arrays. It applies a provided callback function to each element of an array, reducing it to a single value. The callback function takes two parameters: the accumulator (acc) and the current element (curr).

Let’s first understand roles of acc (accumulator) and curr (current element) in the reduce() method:

  1. Accumulator (acc):
  2. The accumulator is a value that accumulates or stores the intermediate result during the iteration process. It can be of any data type (number, string, array, object, etc.). The value of the accumulator is retained and updated for each element in the array as the reduce() method progresses.

  3. Current Element (curr):
  4. The current element represents the current item being processed in the array during each iteration. It changes for each element of the array as the reduce() method traverses through it.

Now, let’s explore some examples to understand the acc and curr parameters:

Example 1: Summing an array of numbers using reduce():

const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((acc, curr) => acc + curr, 0);
console.log(sum); // Output: 15

In this example, the accumulator (acc) initially starts with a value of 0. For each element (curr) in the array, the callback function adds the current element to the accumulator. The updated value of the accumulator is then used in the next iteration. Ultimately, the sum of all elements in the array is obtained.

You need to be logged in to view the rest of the content. Please . Not a Member? Join Us
Scroll to Top