JavaScript array.reduce() method

JavaScript array.reduce() method

array.reduce() method is yet another useful prototype method in JavaScript. We can do lots of important operation with the help of JavaScript reduce method and hence it is very important to know the operations we can perform with the array.reduce() method.

The reduce() method is a prototype method and it can only be call on an array instance and not the Array class.

Syntax

The syntax of the reduce() method is mentioned below

reduce(function callbackFunction(previousValue,currentValue,currentIndex,array) {
  //function logic
},initialValue);

The callback function which is also called the reducer function has the below mentioned parameters -

  1. previousValue - The result of the previous call to the callback function
  2. currentValue - The currentValue of the array item
  3. currentIndex (optional) - This is the index of the currentValue and could be used inside the logic if required.
  4. array (optional) - The array to traverse.

Examples

Let us look into some of the examples of the reduce method.

The examples mentioned below makes use of arrow function and the spread operator. If you are new to arrow function and spread operation I would recommend you to go through them in order to understand the examples in a better way.

Computing the value of all the items in the array. We can do any type of computation and get the final result after each of the items are passed into the callback funtion.

// Array of numbers
let numbers = [1, 2, 3, 4, 5, 6, 7];
// Calculating the sum of the array of numbers
let sum = numbers.reduce(
  (accumulator, currentNumber) => accumulator + currentNumber,
  0
);
console.log("The sum of all the numbers in the array is ", sum);

An important thing to note here in the above example is that the computational capability is not just limited to the mathematical operators or integer operands. The example below shows how we can perform the reduce() method on the array of words to get the final concatenated sentence.

// Array of words
let arrayofwords = ["This", "is", "a", "small", "world"];
// Genrate the sentence from the array of words
let sentence = arrayofwords.reduce(
  (accumulator, currentWord) => accumulator + " " + currentWord,
  ""
);
console.log("The sentence is :", sentence);

The reduce() method can also be used to remove the duplicate values from the array and the below mentioned code is an example of the same.

// Removing duplicate values from the array
let arrayOfDuplicates = [2, 9, 3, 9, 2, 0, 1, 4, 3, 7];
let arrayWithoutDuplicates = arrayOfDuplicates.reduce((accumulator,currentValue)=> {
  if (accumulator.indexOf(currentValue) === -1) {
    accumulator.push(currentValue);
  }
  return accumulator;
},
[]);
console.log("Array without duplicates :", arrayWithoutDuplicates);

We can also retrieve the maximum and minimum values from an array of numbers etc. The example below results into and array which gives the maximum and the minimum marks obtained by a student out of all the subjects.

//Array of the marks received in each of 7 subjects
let marksArray = [61, 45, 94, 49, 78, 40, 89];

//Get the maximum and the minimum marks from the array
let marksMaxMin = marksArray.reduce(
  (accumulator, marks) => [
    Math.max(accumulator[0], marks),
    Math.min(accumulator[1], marks),
  ],
  [0, 100]
);
console.log(marksMaxMin);

We can also calculate the percentage of marks obtained by each student in the array of total marks obtained by each student.

// Total scores received by 5 students
let scores = [470, 600, 550, 450, 399];
// percentage of the scores out of 800
let percentScores = scores.reduce((accumulator, score) => {
  return [...accumulator, (score / 800) * 100];
}, []);
console.log("Array of percentage ", percentScores);

The reduce() method can also be used to group objects by property. The below mentioned example recomputes the array of student objects with student's username.

let students = [
  {
    username: "klebanc",
    name: "Kaye Leblanc",
    age: 27,
    gender: "female",
    company: "ENTALITY",
    email: "kayeleblanc@entality.com",
  },
  {
    username: "nbentley",
    name: "Nona Bentley",
    age: 30,
    gender: "female",
    company: "LEXICONDO",
    email: "nonabentley@lexicondo.com",
  },
  {
    username: "mlang",
    name: "Marks Lang",
    age: 27,
    gender: "male",
    company: "LOVEPAD",
    email: "markslang@lovepad.com",
  },
];

// Generate a new javascript object based on the username so that we can get the details
// based on the username rather than iterating on each element of the array to find out
// the username and the details
let studentDetails = students.reduce((accumulator, student) => {
  return { ...accumulator, [student.username]: student };
}, {});

console.log(studentDetails);

The reduce() method is thus a very efficient way of performing several operation with JavaScript array. It is sometimes used to replace the functionality of array.filter().map() method by giving the result by iterating the array once.

I would recommond using your creativity and thinking of using the reduce() method in the scenarios you come accross while coding in JavaScript.

You can refer to the code from my GitHub Repository - Array Reduce Example

Buy a coffee for sudshekhar