Remove Duplicate Values from an Array in JavaScript
In this tutorial, you will learn how to remove duplicate values from an array in JavaScript.
Remove duplicate values from JS array, How to Remove Duplicates from an Array, javascript remove duplicate objects from array, remove duplicates from array javascript using for loop, set method, filter method, using forEach to remove duplicates.
Checkout more articles on JavaScript
There are multiple ways to remove duplicates from an array and return the unique values. Here we explain you three different ways to do this task.
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.
1 2 3 4 5 | 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.
1 2 3 4 5 | 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.
1 2 3 4 5 | 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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | 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"] |
That’s it for today.
Thank you for reading. Happy Coding!