Javascript Array reduce()

Introduction

Javascript array reduce() method executes a reducer function on each element of the array.

It returns a single value.

arr.reduce(callback(accumulator, currentValue[, index[, array]] )[, initialValue]);
Parameter
Optional
Meaning
callback





Not





a function to execute on array element.
It takes four arguments:
accumulator - the accumulator accumulates callback's return values.
currentValue - the current element.
index - Optional, the index of the current element.
array - Optional, the whole array.
initialValue
Optional
the value to use as the first argument to the first call of the callback.

If no initialValue is supplied, the first element in the array is used and skipped.

The reducer function's returned value is assigned to the accumulator.

Suppose the following use of reduce() occurred:

let r = [0, 1, 2, 3, 4].reduce(function(accumulator, currentValue, currentIndex, array) {
  return accumulator + currentValue
})

The callback would be invoked four times.

iteration accumulator current Value current Index return value
1 0 111
2 1 223
3 3 336
4 6 4410

The following table shows if you put 10 to the initialValue.

[0, 1, 2, 3, 4].reduce((accumulator, currentValue, currentIndex, array) => {
    return accumulator + currentValue
}, 10)
iteration accumulator current Value current Index return value
110 00 10
210 11 11
3 11 2213
413 33 16
5 16 4420

Subtract the numbers in the array, starting from the beginning:

var numbers = [175, 50, 25];

console.log(numbers.reduce(myFunc));/*from w ww .  j a va 2s.co  m*/

function myFunc(total, num) {
  return total - num;
}

Round all the numbers in an array, and display the sum:

var numbers = [15.5, 2.3, 1.1, 4.7];

function getSum(total, num) {
  return total + Math.round(num);
}
console.log(numbers.reduce(getSum, 0));// ww  w  .  ja v  a2  s  . c  o m

Reduce to flat array

const arr = [1, 2, [3, 4]];//from www.j  a va 2 s  .  c  o  m

const a = arr.reduce((acc, val) => acc.concat(val), []);
console.log(a);

Sum all the values of an array

let sum = [0, 1, 2, 3].reduce(function (accumulator, currentValue) {
  return accumulator + currentValue
}, 0)/*  www. j  ava 2  s. c  o m*/
console.log(sum);// sum is 6

Alternatively written with an arrow function:

let total = [ 0, 1, 2, 3 ].reduce(
  ( accumulator, currentValue ) => accumulator + currentValue,
  0/*from   ww  w .  ja v  a  2  s.co  m*/
);
console.log(total);

Sum of values in an object array

let initialValue = 0
let sum = [{x: 1}, {x: 2}, {x: 3}].reduce(function (accumulator, currentValue) {
    return accumulator + currentValue.x
}, initialValue)/*from  ww  w. j a v  a2s . c  o  m*/
console.log(sum) // logs 6

Alternatively written with an arrow function:

let initialValue = 0
let sum = [{x: 1}, {x: 2}, {x: 3}].reduce(
    (accumulator, currentValue) => accumulator + currentValue.x
    , initialValue//from w w w  .  ja va 2 s. c  o m
)
console.log(sum) // logs 6

Counting instances of values in an object

let names = ['CSS', 'Java', 'CSS', 'HTML', 'Java']

let countedNames = names.reduce(function (allNames, name) { 
  if (name in allNames) {
    allNames[name]++/*from   www  .  java 2s.  c om*/
  }
  else {
    allNames[name] = 1
  }
  return allNames
}, {})

console.log(countedNames);

Grouping objects by a property

let langs = [// w  w w . j a v a  2 s.  c  o m
  { name: 'CSS',  age: 21 },
  { name: 'HTML', age: 20 },
  { name: 'Java', age: 20 }
];

function groupBy(objectArray, property) {
  return objectArray.reduce(function (acc, obj) {
    let key = obj[property]
    if (!acc[key]) {
      acc[key] = []
    }
    acc[key].push(obj)
    return acc
  }, {})
}

let groupedLang = groupBy(lang, 'age');
console.log(groupedLang);

Remove duplicate items in array

let myArray = ['a', 'b', 'a', 'b', 'c', 'e', 'e', 'c', 'd', 'd', 'd', 'd']
let myOrderedArray = myArray.reduce(function (accumulator, currentValue) {
  if (accumulator.indexOf(currentValue) === -1) {
    accumulator.push(currentValue)/*  ww  w . j a  v  a2 s  . c  om*/
  }
  return accumulator
}, [])

console.log(myOrderedArray)



PreviousNext

Related