Array Reduce method 5 examples

May 04, 2020

The reduce method applies a function to every item of an array and accumulates the result recursively from a starting point then returns a single value/object.

Some examples of the use of the reduce method

Sum the items of an array:

[3, 5, 4, 3, 6, 2, 3, 4].reduce((a, i) => a + i, 0 );

// For clarity the above code is the same as 
[3, 5, 4, 3, 6, 2, 3, 4].reduce(function(a, i){return (a + i)}, 0 );

Removing duplicates in an array:

let dupes = [1,2,3,'a','a','f',3,4,2,'d','d']
let withOutDupes = dupes.reduce((noDupes, curVal) => {
  if (noDupes.indexOf(curVal) === -1) { noDupes.push(curVal) }
  return accumulator
}, [])

Find the maximum in an array:

[3, 5, 4, 3, 6, 2, 3, 4].reduce((a, i) => Math.max(a, i), -Infinity );

Extract properties in an array of objects returning an array

let obj = [
  {name: 'Alice', job: 'Data Analyst', country: 'AU'},
  {name: 'Bob', job: 'Pilot', country: 'US'},
  {name: 'Karen', job: 'Software Eng', country: 'CA'},
  {name: 'Jeremy', job: 'Artist', country: 'SP'},
]
let ppl = obj.reduce((persons, curPerson) => {
  persons.push([curPerson.name, curPerson.job, curPerson.country])
  return persons
}, [])

Flattened an array of arrays

let flattened = [[3, 4, 5], [2, 5, 3], [4, 5, 6]].reduce(
  (singleArr, nextArray) => singleArr.concat(nextArray), [])
// results is [3, 4, 5, 2, 5, 3, 4, 5, 6]

Ramiro

Hey hi! My name is Ramiro, this is my blog about artificial intelligence, coding and things that are in my head. Follow me on twitter @ramgendeploy so we can chat!