All Articles
Which is Array Reduce method in Javascript
#Web Development

Reduce method in javascript is used to reduce the array to a single value. It takes a callback function which takes four parameters (accumulator, currentValue, index, array), but mostly we use the first two.

Now let's take a look at some of the examples,

Calculate sum of all the elements in an array

const arr = [2, 3, 5, 4];

// here accumulator is names sum
// item is the current value
// 0 is the initial value
const arraySum = arr.reduce((sum, item) => sum + item, 0);
console.log('Output is: ', arraySum);
// Output is: 14

Calculate total number of fruits in the array

const fruits = [
  { name: 'Apple', quantity: 3 },
  { name: 'Banana', quantity: 4 },
  { name: 'Mango', quantity: 2 },
];

const totalFruits = fruits.reduce((total, fruit) => total + fruit.quantity, 0);
console.log('Total Fruits are:', totalFruits);
// Total Fruits are: 9

Group Students by ClassName

const students = [
  { name: 'Baljeet', className: 10 },
  { name: 'Fatehjit', className: 2 },
  { name: 'Ekjeet', className: 10 },
  { name: 'Manvir', className: 5 },
];
const output = students.reduce((groupedStudents, student) => {
  const className = student.className;
  if (groupedStudents[className] == null) {
    groupedStudents[className] = [];
  }
  groupedStudents[className].push(student);
  return groupedStudents;
}, {});
console.log('Grouped Students: ', output);
/* output
{ 2: [ { name: 'Fatehjit', className: 2 } ],
  5: [ { name: 'Manvir', className: 5 } ],
  10: [ { name: 'Baljeet', className: 10 },
     { name: 'Ekjeet', className: 10 } ] } */

2019-2024 Baljeet Singh. All rights reserved.