Remove Duplicates From Array
Example
Input:
1[1, 2, 2, 3, 3, 3, 4, 4, 4, 5, 6, 6, 6];
Output:
1[1, 2, 3, 4, 5, 6];
Solution
- Use
filter
andindexOf
1function removeDuplicatesFromArray(input) {2 return input.filter((item, index) => input.indexOf(item) == index);3}
- Use
object
to mark if an item has appeared
1function removeDuplicatesFromArray(input) {2 var unique = {};34 input.forEach(item => {5 if (!unique[item]) {6 unique[item] = true;7 }8 });910 return Object.keys(unique);11}
- Create an array from
Set
1function removeDuplicatesFromArray(input) {2 return Array.from(new Set(input));3}