Last active
October 3, 2018 14:52
-
-
Save davidicus/4fcc17cc123310d704ad807afd9168a5 to your computer and use it in GitHub Desktop.
Array Reduce examples and use cases
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Flatten array | |
var flattened = [[0, 1], [2, 3], [4, 5]].reduce( | |
( accumulator, currentValue ) => accumulator.concat(currentValue), | |
[] | |
); | |
// flattened is [0, 1, 2, 3, 4, 5] | |
// Remove duplicate items in an array | |
let arr = [1, 2, 1, 2, 3, 5, 4, 5, 3, 4, 4, 4, 4]; | |
let result = arr.sort().reduce((accumulator, current) => { | |
const length = accumulator.length | |
if (length === 0 || accumulator[length - 1] !== current) { | |
accumulator.push(current); | |
} | |
return accumulator; | |
}, []); | |
console.log(result); //[1,2,3,4,5] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment