Array reduce() Method

Introduction

The reduce() method in JavaScript is used to reduce an array to a single value by executing a callback function on each element of the array. The callback function takes in four parameters: the accumulator, the current value, the current index, and the array itself. The reduce() method iterates over the array from left to right and accumulates the values returned by the callback function.

Syntax

The syntax of the `reduce()` method is as follows:

array.reduce(callback(accumulator, currentValue, currentIndex, array), initialValue)

Parameters:

  • callback: The function to execute on each element of the array. It takes in the accumulator, the current value, the current index, and the array itself.
  • accumulator: It accumulates the return values of the callback function.
  • currentValue: The current element being passed from the array.
  • currentIndex (optional): The index of the current element being processed.
  • array (optional): The array on which the `reduce()` method was called.
  • initialValue (optional): A value that will be passed as the first argument to the first call of the callback function. If not provided, the first element acts as the accumulator on the first call and callback() won't execute on it.

Usage

The reduce() method executes a reducer function on each element of the array and returns a single output value. Let's take a look at some examples that demonstrate the usage of the `reduce()` method.

Example 1: Sum of All Values of Array

const numbers = [1, 2, 3, 4, 5, 6];
 
function sum_reducer(accumulator, currentValue) {
  return accumulator + currentValue;
}
 
let sum = numbers.reduce(sum_reducer);
console.log(sum); // 21
 
// using arrow function
let summation = numbers.reduce(
  (accumulator, currentValue) => accumulator + currentValue
);
console.log(summation); // 21

Example 2: Finding Maximum Value

const numbers = [10, 5, 20, 25, 15];
 
const max = numbers.reduce((accumulator, currentValue) => {
  return Math.max(accumulator, currentValue);
});
 
console.log(max); // Output: 25

Example 3: Counting Occurrences

const fruits = ['apple', 'banana', 'orange', 'banana', 'apple'];
 
const count = fruits.reduce((accumulator, currentValue) => {
  accumulator[currentValue] = (accumulator[currentValue] 
 0) + 1;
  return accumulator;
}, {});
 
console.log(count);
// Output: { apple: 2, banana: 2, orange: 1 }

Example 4: Join each string elements

const message = ["JavaScript ", "is ", "fun."];
 
// function to join each string elements
function joinStrings(accumulator, currentValue) {
  return accumulator + currentValue;
}
 
// reduce join each element of the string
let joinedString = message.reduce(joinStrings);
console.log(joinedString);
 
// Output: JavaScript is fun.

Example 5: Subtracting Numbers in Array

const numbers = [1800, 50, 300, 20, 100];
 
// subtract all numbers from first number
// since 1st element is called as accumulator rather than currentValue
// 1800 - 50 - 300 - 20 - 100
let difference = numbers.reduce(
  (accumulator, currentValue) => accumulator - currentValue
);
console.log(difference); // 1330
 
const expenses = [1800, 2000, 3000, 5000, 500];
const salary = 15000;
 
// function that subtracts all array elements from given number
// 15000 - 1800 - 2000 - 3000 - 5000 - 500
let remaining = expenses.reduce(
  (accumulator, currentValue) => accumulator - currentValue,
  salary
);
console.log(remaining); // 2700

This example clearly explains the difference between passing an initialValue and not passing an initialValue.

Example 6: Remove Duplicate Items from Array

let ageGroup = [18, 21, 1, 1, 51, 18, 21, 5, 18, 7, 10];
let uniqueAgeGroup = ageGroup.reduce(function (accumulator, currentValue) {
  if (accumulator.indexOf(currentValue) === -1) {
    accumulator.push(currentValue);
  }
  return accumulator;
}, []);
 
console.log(uniqueAgeGroup); // [ 18, 21, 1, 51, 5, 7, 10 ]

Example 7: Grouping Objects by a property

let people = [
  { name: "John", age: 21 },
  { name: "Oliver", age: 55 },
  { name: "Michael", age: 55 },
  { name: "Dwight", age: 19 },
  { name: "Oscar", age: 21 },
  { name: "Kevin", age: 55 },
];
 
function groupBy(objectArray, property) {
  return objectArray.reduce(function (accumulator, currentObject) {
    let key = currentObject[property];
    if (!accumulator[key]) {
      accumulator[key] = [];
    }
    accumulator[key].push(currentObject);
    return accumulator;
  }, {});
}
 
let groupedPeople = groupBy(people, "age");
console.log(groupedPeople);

Output:

{
  '19': [ { name: 'Dwight', age: 19 } ],
  '21': [ { name: 'John', age: 21 }, { name: 'Oscar', age: 21 } ],
  '55': [
    { name: 'Oliver', age: 55 },
    { name: 'Michael', age: 55 },
    { name: 'Kevin', age: 55 }
  ]
}

Note

  • Calling reduce() on an empty array without initialValue will throw TypeError.
  • reduce() executes the given function for each value from left to right.
  • reduce() does not change the original array.
  • It is almost always safer to provide initialValue.

Key Takeaways

  • The reduce() method in JS reduces an array into a single value using callback function.
  • Syntax: array.reduce(callback(accumulator, currentValue, currentIndex, array), initialValue)
  • The callback function takes four arguments: 'accumulator', 'currentValue', 'currentIndex', and 'array'.
  • The reduce() method can be used to perform various operations on arrays such as summing up elements, finding maximum or minimum values, counting occurrences, and more.
  • If an initial value is not provided, the first element of the array is used as the initial accumulator value.

Comments

Popular posts from this blog

Mastering JavaScript Output: Communicating with Users

What is JIT compiler? Is JavaScript compiled or interpreted or both?

'for in' Loop