How to Remove duplicate elements from array in JavaScript ?
There are multiple ways to remove duplicate elements from an array in JavaScript:
- Using Set: We can use the Set object to remove duplicate elements from an array. The Set object only stores unique values, so we can convert the array to a Set and then back to an array to remove duplicates.
Example:
let arr = [1, 2, 3, 3, 4, 4, 5];
let uniqueArr = [...new Set(arr)];
console.log(uniqueArr); // Output: [1, 2, 3, 4, 5]
- Using filter() and indexOf(): We can use the filter() method to create a new array with only the unique elements. We can use the indexOf() method to check if an element already exists in the new array.
Example:
let arr = [1, 2, 3, 3, 4, 4, 5];
let uniqueArr = arr.filter((elem, index) => {
return arr.indexOf(elem) === index;
});
console.log(uniqueArr); // Output: [1, 2, 3, 4, 5]
- Using reduce() and includes(): We can use the reduce() method to iterate over the array and create a new array with only the unique elements. We can use the includes() method to check if an element already exists in the new array.
Example:
let arr = [1, 2, 3, 3, 4, 4, 5];
let uniqueArr = arr.reduce((acc, curr) => {
if (!acc.includes(curr)) {
acc.push(curr);
}
return acc;
}, []);
console.log(uniqueArr); // Output: [1, 2, 3, 4, 5]