An Interest In:
Web News this Week
- April 20, 2024
- April 19, 2024
- April 18, 2024
- April 17, 2024
- April 16, 2024
- April 15, 2024
- April 14, 2024
September 20, 2021 05:03 pm GMT
Original Link: https://dev.to/ramgendeploy/learn-javascript-reduce-method-with-5-examples-128n
Learn Javascript Reduce method with 5 examples
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 );
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 );
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}, [])
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 maplet pplm = obj.map((curPerson)=>[curPerson.name, curPerson.job, curPerson.country])
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]
Original Link: https://dev.to/ramgendeploy/learn-javascript-reduce-method-with-5-examples-128n
Share this article:
Tweet
View Full Article
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To