3

Learn Javascript Reduce method with 5 examples

 2 years ago
source link: https://dev.to/ramgendeploy/learn-javascript-reduce-method-with-5-examples-128n
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

The reduce method applies a function to every item of an array and accumulates the result iteratively 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 );
Enter fullscreen modeExit fullscreen mode

Find the maximum in an array:

Here in each iteration we return the max between the accumulator and the current item and in the end we have the max of the entire array.

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

Removing duplicates in an array:

We check if the current value has index on the accumulator array if not is going to return -1 hence is not in the array and we can add it.

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 noDupes
}, [])
Enter fullscreen modeExit fullscreen mode

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
}, [])

// You can also do this with map
let pplm = obj.map((curPerson)=>[curPerson.name, curPerson.job, curPerson.country])
Enter fullscreen modeExit fullscreen mode

Flattened an array of arrays

This is only 1 level deep but it you can adapt this with a recursive function, but i'm not that fan of making recursive things on javascript 😂

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]
Enter fullscreen modeExit fullscreen mode

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK