Commonly asked Javascript interview questions to remove duplicates from an array.
Here are different ways to remove duplicates from an array and return only the unique values.
1) Using Set
ES6 provides a new type named Set that stores a collection of unique values of any type. A set is a collection of items that are unique.
var arr = [1, 2, 3, 4, 5, 3, 2, 1];
// using set
console.log([...new Set(arr)]);
2) Using Filter
The filter() method creates an array filled with all array elements that pass a condition
var arr = [1, 2, 3, 4, 5, 3, 2, 1];
// Remove duplicate using filter
console.log(arr.filter((value, index) => arr.indexOf(value) === index));
3) Using forEach & includes
We can iterate over the elements in the array using forEach, and we will push into the new array if it doesn’t exist in the array.
// Using includes
var arr = [1, 2, 3, 4, 5, 3, 2, 1];
let unique = [];
arr.forEach((element) => {
if (!unique.includes(element)) {
unique.push(element);
}
});
console.log(unique);
4) Using reduce
The reduce() method reduces the array to a single value. The reduce() method executes a provided function for each value of the array.
var arr = [1, 2, 3, 4, 5, 3, 2, 1];
// Using reduce
let dupReduce = arr.reduce(function (a, b) {
if (a.indexOf(b) < 0) a.push(b);
return a;
}, []);
console.log(dupReduce);
That's all! I hope this article might be helpful to remove duplicates from an array in javascript.
Thanks for reading :)