Skip to content

Instantly share code, notes, and snippets.

@davidicus
Last active October 3, 2018 14:52
Show Gist options
  • Save davidicus/4fcc17cc123310d704ad807afd9168a5 to your computer and use it in GitHub Desktop.
Save davidicus/4fcc17cc123310d704ad807afd9168a5 to your computer and use it in GitHub Desktop.
Array Reduce examples and use cases
// 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