How to remove duplicates from an Array in JavaScript
In this article, you will show you how to remove duplicates from an Array in JavaScript.
- JavaScript Spread Operator
- ES6 Rest Parameter in JavaScript
- JavaScript Arrow function
- Difference between var, let and const in JavaScript
- How to get the current URL using JavaScript
Way to remove duplicate values from an array in JavaScript
1. Set()
In our opinion set method is the simplest and shortest way to get unique values. ES6 provides the Set object which lets you store unique values. We just need to pass an array as a parameter to set object, it will remove the duplicate values.
var colors = ["Blue","Green","Yellow","Pink","Green"];
var uniqueColors = [...new Set(colors)];
console.log(uniqueColors);
// Output: ["Blue", "Green", "Yellow", "Pink"]
Here, first we create set object by passing an array so, duplicate values will be removed. Then using spread operator (…) , we convert it back to an array.
Also you can use Array.form() to convert a Set into an array.
var colors = ["Blue","Green","Yellow","Pink","Green"];
var uniqueColors = Array.from(new Set(colors));
console.log(uniqueColors);
// Output: ["Blue", "Green", "Yellow", "Pink"]
2. filter()
Using filter()
method, you can also remove duplicate values from an array. See below example.
var colors = ["Blue","Green","Yellow","Pink","Green"];
var x = (colors) => colors.filter((v,i) => colors.indexOf(v) === i);
x(colors);
// Output: ["Blue", "Green", "Yellow", "Pink"]
3. forEach()
forEach()
is another way to filter out duplicates and returns unique values.
function removeDuplicates(array){
var colorArray = [];
for(i=0; i < array.length; i++){
if(colorArray.indexOf(array[i]) === -1) {
colorArray.push(array[i]);
}
}
return colorArray;
}
var colors = ["Blue","Green","Yellow","Pink","Green"];
var uniqueColor = removeDuplicates(colors)
console.log(uniqueColor);
// Output: ["Blue", "Green", "Yellow", "Pink"]
Thank you for reading. Happy Coding..!!