What is the method to remove duplicates in an ES6 array…
There are several common methods for removing duplicate elements from an array in ES6.
- By using Set: The Set object in ES6 is an ordered collection of unique values, which can be used to remove duplicate items from an array. Converting the array to a Set object and then back to an array can easily remove duplicates.
const arr = [1, 2, 3, 3, 4, 4, 5];
const uniqueArr = Array.from(new Set(arr));
console.log(uniqueArr); // [1, 2, 3, 4, 5]
- Use the Array.prototype.filter() and Array.prototype.indexOf() methods to remove duplicates by filtering out the first occurrence of each element in the array.
const arr = [1, 2, 3, 3, 4, 4, 5];
const uniqueArr = arr.filter((item, index) => arr.indexOf(item) === index);
console.log(uniqueArr); // [1, 2, 3, 4, 5]
- Use the Array.prototype.reduce() method to iterate through an array and add non-repeating elements to the result array.
const arr = [1, 2, 3, 3, 4, 4, 5];
const uniqueArr = arr.reduce((prev, current) => {
if (!prev.includes(current)) {
prev.push(current);
}
return prev;
}, []);
console.log(uniqueArr); // [1, 2, 3, 4, 5]
The choice of method for deduplicating arrays depends on specific needs and performance requirements.