Last active
September 4, 2019 14:59
-
-
Save BeSublime/da0fc51ed73f7ddd31e54c43a76d7496 to your computer and use it in GitHub Desktop.
Handy JavaScript Snippets
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
| // 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