JavaScript Reduce Method

Usage, advantages and real-world examples of the JavaScript reduce method.

The reduce method executes a function for each value of the array, eventually reducing the array to a single value. The return value of the method is stored in its first parameter, the accumulator parameter.

For example:

const array1 = [1, 2, 3, 4, 5, 6]

// 0 + 1 + 2 + 3 + 4 + 5 + 6
const initialValue = 0
const sum = array1.reduce((accumulator, currentValue) => accumulator + currentValue)

console.log(sumWithInitial)
// Expected output: 21

The initial value variable in the reduce function is not mandatory, but giving an initial value will reduce the possibility of errors.

For example:

const array1 = [1, 2, 3, 4, 5, 6]

// 0 + 1 + 2 + 3 + 4 + 5 + 6
const initialValue = 0
const sumWithInitial = array1.reduce(
  (accumulator, currentValue) => accumulator + currentValue,
  initialValue
)
console.log(sumWithInitial)
// Expected output: 21

We can also use the object in the reduce function. Let's calculate the total for a shopping cart app.

const basket = [
  { id: 1, name: 'aaa', price: 50, quantity: 2 },
  { id: 2, name: 'bbb', price: 150, quantity: 4 },
  { id: 3, name: 'ccc', price: 50 },
  { id: 4, name: 'ddd', price: 450, quantity: 2 },
  { id: 5, name: 'eee', price: 75, quantity: 4 },
]

const total = basket.reduce((acc, obj) => acc + obj.price * (obj.quantity || 1), 0)

console.log(total)
// Expected output: 1950

Let's calculate the number of repeating values in an array.

const categories = ['NextJS', 'NodeJS', 'ReactJS', 'NodeJS', 'NextJS', 'NextJS']

const countedCategories = categories.reduce(function (allCategories, category) {
  if (category in allCategories) {
    allCategories[category]++
  } else {
    allCategories[category] = 1
  }
  return allCategories
}, {})

console.log(countedCategories)
// Expected output: {NextJS: 3, NodeJS: 2, ReactJS: 1}

Let's delete repeating values in an array.

const categories = ['NextJS', 'NodeJS', 'ReactJS', 'NodeJS', 'NextJS', 'NextJS']

const editedCategory = categories.reduce(function (allCategories, category) {
  if (!allCategories.includes(category)) {
    allCategories.push(category)
  }
  return allCategories
}, [])

console.log(editedCategory)
// Expected output: [ 'NextJS', 'NodeJS', 'ReactJS' ]

Now let's group the employees according to their departments.

  const departments = [
    {
      name: 'Metin İRTEMEK',
      department: 'IT',
    },
    {
      name: 'Nizamettin AYDIN',
      department: 'Marketing',
    },
    {
      name: 'Kemalettin YILMAZ',
      department: 'Production',
    },
    {
      name: 'Hüsamettin UYANIK',
      department: 'IT',
    },
    {
      name: 'Şerafettin MUMCU',
      department: 'IT',
    },
    {
      name: 'Fahrettin UZUN',
      department: 'Production',
    },
  ]

  const groupBy = (array, prop) => {
    return array.reduce((acc, obj) => {
      let key = obj[prop]
      if (!acc[key]) {
        acc[key] = []
      }
      acc[key].push(obj)
      return acc
    }, {})
  }

  let groupedDepartments = groupBy(departments, 'department')

  console.log(groupedDepartments)

  // Expected output:
  {
    IT: [
      { name: 'Metin İRTEMEK', department: 'IT' },
      { name: 'Hüsamettin UYANIK', department: 'IT' },
      { name: 'Şerafettin MUMCU', department: 'IT' },
    ],
    Marketing: [{ name: 'Nizamettin AYDIN', department: 'Marketing' }],
    Production: [
      { name: 'Kemalettin YILMAZ', department: 'Production' },
      { name: 'Fahrettin UZUN', department: 'Production' },
    ],
  }

With the Reduce method, we can code complex operations in a more practical way. I think these examples are enough for now.