Skip to content

Instantly share code, notes, and snippets.

@BeSublime
Last active March 3, 2020 18:10
Show Gist options
  • Select an option

  • Save BeSublime/0a59a30309f4fe4e6e10be084889c451 to your computer and use it in GitHub Desktop.

Select an option

Save BeSublime/0a59a30309f4fe4e6e10be084889c451 to your computer and use it in GitHub Desktop.
Remove duplicates from an array (multiple approaches)
// Removes duplicate items from an array.
//
// Credit to this awesome article by Samantha Ming (@samantha_ming)
// https://medium.com/dailyjs/how-to-remove-array-duplicates-in-es6-5daa8789641c
const array = ['🦙', 1, 1, 2, '🦙', '🦙', 3];
// Using Set (requires ES6)
let uniqueSet = new Set(array);
let arrayFromSet = [...uniqueSet];
// Using Array.filter()
let filteredArray = array.filter(function(item, index) {
return array.indexOf(item) === index;
});
// or, with ES6 support, using an arrow function to shorten
let filteredArrayES6 = array.filter((item, index) => array.indexOf(item) === index);
// Using Array.reduce()
let reducedArray = array.reduce(function(accumulator, currentItem) {
if (accumulator.indexOf(currentItem) === -1) {
accumulator.push(currentItem);
}
return accumulator;
}, []);
// or, with ES6 support, using an arrow function and Array.includes()
let reducedArrayES6 = array.reduce((accumulator, currentItem) => {
return unique.includes(currentItem) ? accumulator : [...accumulator, currentItem]
}, []);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment