Another very common situation is to remove repeated values from an array.
Let’s show some of the approaches you can use:
The Set
object lets you store unique values of any type, whether primitive values or object references.
const arr = ["a", 2, "c", 4, "a", 2, 2, 5, "c"];
const set1 = new Set(arr);
const result1 = [...set1.values()];
console.log(result1);
//[ 'a', 2, 'c', 4, 5 ]
const result2 = [...new Set(arr)];
console.log(result2);
//[ 'a', 2, 'c', 4, 5 ]
We just go over the array and verify if the starting position of each element in the array is identical to the current position for each element. For duplicate items, these two locations are obviously different.
const arr = ["a", 2, "c", 4, "a", 2, 2, 5, "c"];
const filtered = arr.filter((item, index) => arr.indexOf(item) === index);
console.log(filtered);
//[ 'a', 2, 'c', 4, 5 ]
Leave a Reply