Must Read: Reduce Function in JavaScript with 15+ Examples

In this blog, we will learn about reduce() function in JavaScript (ES6). The reduce() method on arrays executes a reducer function on all the elements of the given array in the order, passing the return value from the earlier reducer call to the later reducer call.

This function makes your code more readable when combined with other programming abstractions. The reduce() method returns a single value after accumulating the result of an array. This method doesn’t work for empty arrays, and also it doesn’t change the original array.

Reduce() Function in JavaScript Examples

1. Sum of Array JavaScript using Reduce()

Code Summing an Array of numbers:

// with ES6 Reduce Method

Example 1:
function sum(arr) {
  const reducer = (sum, val) => sum + val;
  const initialValue = 0;
  return arr.reduce(reducer, initialValue);
}

sum([1, 4, 5, 8]); //Output: 18

Example 2:
const numbers = [1, 2, 3];
const sum = numbers.reduce(function(sum, number) {
  const updatedSum = sum + number;
  return updatedSum;
}, 0);
console.log(sum); //Output: 6

// without using Reduce Method

function sum(arr) {
  let sum = 0;
  for (const val of arr) {
    sum += val;
  }
  return sum;
}

sum([1, 4, 5, 8]); //Output: 18

The reduce() method had 2 parameters, one is reducer() function and second one is an arbitrary initialValue. reducer() function is called and each element on the array adds up with the accumulator. Accumulator starts as the initialValue.

Reduce() Working Explained:

array.reduce(function(accumulator, item, index, array) {
// Use accumulator and item
// to calculate updatedAccumulator
return updatedAccumulator;
})
  1. 0+1 = sum
  2. Sum + 4 = Sum = 5
  3. Sum + 5 = Sum = 10
  4. Sum + 8 = Sum = 18

Hope this step was clear to you.

2. Using Array Reduce function without Initial Value

Omitting initial value argument:


const numbers = [2, 4, 6];
const sum = numbers.reduce(function summarize(sum, number, index) {
  console.log(index); // logs 1, 2
  return sum + number;
});
sum; // 12

3. Sum on Array of Object using Reduce() in JS

Code to calculate sum of an array of object:


// Normal Approach
const lineItems = [
{ description: 'Banana (Dozen)', quantity: 1, price: 3, total: 3 },
{ description: 'Cheese', quantity: 0.5, price: 5, total: 2.5 },
{ description: 'Butter', quantity: 2, price: 6, total: 12 }
];

lineItems.reduce((sum, li) => sum + li.total, 0);  // Output: 17.5

// Alternative Approach

const lineItems = [
  { description: 'Eggs (Dozen)', quantity: 1, price: 3, total: 3 },
  { description: 'Cheese', quantity: 0.5, price: 5, total: 2.5 },
  { description: 'Butter', quantity: 2, price: 6, total: 12 }
];

lineItems.map(li => li.total).reduce((sum, val) => sum + val, 0);
 //Output: 17.5

Here we are calculating the sum of each line item’s total property.

There are many more applications where we can use the reduce() method. In some problems, they prove to be beneficial whereas in some problems, we can look for alternatives for a simpler approach. It depends on the programmer and the problem statement after all.

4. Find the Maximum Value using Reduce Method (without using Loop)


Example 1:
const dates = [
  '2019/06/01',
  '2018/06/01',
  '2019/09/01', // This is the most recent date, but how to find it?
  '2018/09/01'
].map(v => new Date(v));

// This works because you can compare JavaScript dates using `>` and `<`.
// So `a > b` if and only if `a` is after `b`.
const maxDate = dates.reduce((max, d) => d > max ? d : max, dates[0]);

Example 2:

const students = [
    { name: "Kingsley", score: 70 },
    { name: "Jack", score: 80 },
    { name: "Joe", score: 63 },
    { name: "Beth", score: 75 },
    { name: "Kareem", score: 59 },
    { name: "Sarah", score: 93 }
]
 
const max = students.reduce((acc, student) => {
    if(acc === null || student.score > acc) 
        return student.score
    return acc
}, null)
 
console.log(max) // Prints 93

5. Find the Minimum Value using Reduce Method (without using Loop)


const students = [
    { name: "Kingsley", score: 70 },
    { name: "Jack", score: 80 },
    { name: "Joe", score: 63 },
    { name: "Beth", score: 75 },
    { name: "Kareem", score: 59 },
    { name: "Sarah", score: 93 }
]

const min = students.reduce((acc, student) => {
    if (acc === null || student.score < acc) {
        return student.score
    } 
    return acc
}, null)
 
console.log(min) // Prints 59

6. Grouping Values (Group / Count No. of Items with Same Value)

Counting Occurrences of Items in an Array Using reduce()


Example 1:
const characters = [
  { name: 'Jean-Luc Picard', age: 59 },
  { name: 'Will Riker', age: 29 },
  { name: 'Deanna Troi', age: 29 }
];

// Start with an empty object, increment `map[age]` for each element
// of the array.
const reducer = (map, val) => {
  if (map[val] == null) {
    map[val] = 1;
  } else {
    ++map[val];
  }
  return map;
};
characters.map(char => char.age).reduce(reducer, {});
 // Output: { 29: 2, 59: 1 }

Example 2:
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 of Example 2:
{
  '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 }
  ]
}

Example 3:

let student = [
  { name: 'David', age: 23, hobby: 'fishing' },
  { name: 'Rachel', age: 25, hobby: 'cooking' },
  { name: 'Rahul', age: 22, hobby: 'fishing' }
];

function myFunc(obj, prop) {
  return obj.reduce(function (acc, item) {
    let key = item[prop]
    if (!acc[key]) {
      acc[key] = []
    }
    acc[key].push(item)
    return acc
  }, {})
}

let groupedStudent = myFunc(student, 'hobby')
console.log(groupedStudent)

Output:
{
  "fishing": [
    {
      "name": "David",
      "age": 23,
      "hobby": "fishing"
    },
    {
      "name": "Rahul",
      "age": 22,
      "hobby": "fishing"
    }
  ],
  "cooking": [
    {
      "name": "Rachel",
      "age": 25,
      "hobby": "cooking"
    }
  ]
}

7. JavaScript Array reduceRight() method


let numbers = [1, 2, 3];

let sum = numbers.reduceRight(function (previousValue, currentValue) {
  console.log({ previousValue, currentValue });
  return previousValue + currentValue;
});

console.log(`Result: ${sum}`); // Result: 6 

8. Subtracting Numbers in Array using Reduce() Method


Example 1: 
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

Example 2: 
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

9. Remove Duplicate Items from Array in JS


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 ]

10. JavaScript Average Array using Reduce()


const euros = [29.76, 41.85, 46.5];

const average = euros.reduce((total, amount, index, array) => {
  total += amount;
  if( index === array.length-1) { 
    return total/array.length;
  }else { 
    return total;
  }
});

average // 39.37

11. Double the Array values using Reduce()


const euros = [29.76, 41.85, 46.5];

const doubled = euros.reduce((total, amount) => {
  total.push(amount * 2);
  return total;
}, []);

doubled // [59.52, 83.7, 93]

12. Filter Array Items using Reduce()


const euro = [29.76, 41.85, 46.5];

const newVal = euro.reduce((total, amount) => {
  if (amount > 30) {
    total.push(amount);
  }
  return total;
}, []);

newVal // [ 41.85, 46.5 ]

13. Tally / Count number of Repeated Items in Array and create a new object

Example 1:
const fruitBasket = ['banana', 'cherry', 'orange', 'apple', 'cherry', 'orange', 'apple', 'banana', 'cherry', 'orange', 'fig' ];

const count = fruitBasket.reduce( (tally, fruit) => {
  tally[fruit] = (tally[fruit] || 0) + 1 ;
  return tally;
} , {})

count // { banana: 2, cherry: 3, orange: 3, apple: 2, fig: 1 }

Example 2:
const fruits = [ 'Banana', 'Orange', 'Apple', 'Orange', 'Pear', 'Banana']
 
const occurrences = fruits.reduce((acc, currFruit) => {
    return {...acc, [currFruit]: (acc[currFruit] || 0) + 1 }
}, {})
 
console.log(occurrences);
 
/*
{
  Apple: 1,
  Banana: 2,
  Orange: 2,
  Pear: 1
}
*/

Example 3:

let myCars = ['Mercedes-Benz', 'Jeep', 'Ferrari', 'Lamborghini', 'Mercedes-Benz', 'BMW', 'Ferrari']
let instances = myCars.reduce(function (allCars, car) {
  if (car in allCars) {
    allCars[car]++
  }
  else {
    allCars[car] = 1
  }
  return allCars
}, {})
console.log(instances);


'{"Mercedes-Benz":2,"Jeep":1,"Ferrari":2,"Lamborghini":1,"BMW":1}'

14. Flattening an Array of Arrays in JavaScript


Example 1:
const data = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];

const flat = data.reduce((total, amount) => {
  return total.concat(amount);
}, []);

flat // [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]

Example 2 (without Unique):
const data = [
  {a: 'happy', b: 'robin', c: ['blue','green']}, 
  {a: 'tired', b: 'panther', c: ['green','black','orange','blue']}, 
  {a: 'sad', b: 'goldfish', c: ['green','red']}
];

const colors = data.reduce((total, amount) => {
  amount.c.forEach( color => {
      total.push(color);
  })
  return total;
}, [])

colors //['blue','green','green','black','orange','blue','green','red']

Example 3 (with Unique):

const data = [
  {a: 'happy', b: 'robin', c: ['blue','green']}, 
  {a: 'tired', b: 'panther', c: ['green','black','orange','blue']}, 
  {a: 'sad', b: 'goldfish', c: ['green','red']}
];

const uniqueColors = data.reduce((total, amount) => {
  amount.c.forEach( color => {
    if (total.indexOf(color) === -1){
     total.push(color);
    }
  });
  return total;
}, []);

uniqueColors // [ 'blue', 'red', 'green', 'black', 'orange']

Example 4:
const arrOfArrs = [
    ['aaron', 'ake', 'anna', 'aje'],
    ['becky', 'ben', 'bright'],
    ['cara', 'chris'],
    ['david', 'daniel', 'danielle', 'djenue'],
]
 
const flattened = arrOfArrs.reduce((acc, array) => acc.concat(array))
 
console.log(flattened)
 
// ["aaron", "ake", "anna", "aje", "becky", "ben", "bright", "cara", "chris", "david", "daniel", // "danielle", "djenue"]

15. Sum in an Object Array Using Array Reduce Method


let initialValue = 0
let obj = [{n: 5}, {n: 9}, {n: 13}, {n: 25}, {n: 40}]
let sum = obj.reduce(function (accumulator, curValue) {
    return accumulator + curValue.n
}, initialValue)

console.log(sum);

// 92

The reduce() function is sometimes more confusing too than being helpful. For example, if we want to get the sum of all the numbers in an array, a for loop is recommended rather than going for the reduce() method. If we have to use filter() or map() method, then it’s better to use reduce() function.

Hope the article was informative and you learnt something new in this.

Leave a Comment