Reduce Function In Javascript

Rakesh YadavRakesh Yadav
2 min read

In JavaScript, the reduce() function is a higher-order function that is used to reduce an array to a single value. It iterates over the elements of an array, applying a callback function to each element, and accumulating the result into a single value. The reduce() function takes a callback function as its first parameter and an optional initial accumulator value as its second parameter.

Here's the basic syntax of the reduce() function:

array.reduce(callback, initialValue);
  • array: The array to be reduced.

  • callback: A function that is called for each element in the array, taking four arguments: accumulator, currentValue, currentIndex, and array.

  • initialValue (optional): An initial value for the accumulator. If provided, the reduce operation starts with this initial value. If not provided, the first element of the array is used as the initial accumulator value.

Here's an example to illustrate how to use the reduce() function:

// Example 1: Summing an array of numbers
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0);

console.log(sum); // Output: 15

// Example 2: Flattening an array of arrays
const nestedArrays = [[1, 2], [3, 4], [5, 6]];
const flattenedArray = nestedArrays.reduce((accumulator, currentValue) => accumulator.concat(currentValue), []);

console.log(flattenedArray); // Output: [1, 2, 3, 4, 5, 6]

// Example 3: Counting the occurrences of each element in an array
const fruits = ['apple', 'banana', 'orange', 'apple', 'banana', 'apple'];
const fruitCount = fruits.reduce((accumulator, fruit) => {
  accumulator[fruit] = (accumulator[fruit] || 0) + 1;
  return accumulator;
}, {});

console.log(fruitCount);
// Output: { apple: 3, banana: 2, orange: 1 }

In the first example, the reduce() function is used to calculate the sum of an array of numbers. In the second example, it flattens a nested array. In the third example, it counts the occurrences of each element in an array using an object as an accumulator.

The reduce() function is versatile and can be used for a wide range of tasks where you need to accumulate values while iterating over an array.

0
Subscribe to my newsletter

Read articles from Rakesh Yadav directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Rakesh Yadav
Rakesh Yadav