There are various methods to Remove Duplicates from An Array in JavaScript. We will discuss the most common methods from them.

What are Duplicates in An Array?
Duplicate values are those values which are presented more than one time in the array. So in this tutorial we will remove those duplicate values from the array using JavaScript.
There are various approaches to Remove Duplicates From An Array In JavaScript, those are below:
Using Set()
You can remove duplicates from an array using Set(), because you know that Set only supports unique values. So it will remove all the values which are already in that array.
const numbers = [1, 2, 1, 3, 11 ,4 ,4 ,5 ,5 ,5, 6, 6, 7]
console.log(Array.from(new Set(numbers)));
Ans:
= [1, 2, 3, 11, 4, 5, 6, 7]
Using for() loop, To remove Duplicates From An Array in JavaScript
- Traverse the array using the for loop.
- Create a temp array to store only unique values.
- Use indexOf() method to check the values in the temp array if doesn’t exist (if indexOf() returns -1 )t then push that value into the temp array
const numbers = [1, 2, 3, 1, 2, 4, 5, 2, 3, 6, 8, 5 , 6]
for (let i = 0; i < numbers.length; i++) {
var index = temp.indexOf(numbers[i])
if(index == -1){
temp.push(numbers[i])
}
}
console.log(temp);
Answer: [ 1, 2, 3, 4, 5, 6, 8 ]
Filter method to remove duplicates in JavaScript
This filter() method creates a new array for which we provide the condition inside it. It will include those elements for which the condition returns true. So we can remove the duplicates from the array by providing the condition in JavaScript.
const numbers = [1, 2, 3, 1, 2, 4, 5, 2, 3, 6, 8, 5 , 6]
var temp = [];
function removeDuplicates (){
return numbers.filter((item, index) => numbers.indexOf(item) === index)
}
console.log(removeDuplicates());
Answer:
[1, 2, 3, 4, 5, 6, 8]
Using Includes Method to Remove Duplicates from JavaScript Array
JavaScript includes() method checks that the value is present in that array or not. If the value is not present in the third array then we will push the value into the third array and will return that array.
const numbers = [1, 2, 3, 1, 2, 4, 5, 2, 3, 6, 8, 5 , 6]
function removeDuplicates (){
var temp = [];
numbers.forEach((value)=>{
if(!temp.includes(value)){
temp.push(value)
}
})
return temp;
}
console.log(removeDuplicates());
Answer:
[1, 2, 3, 4, 5, 6, 8]
You can see more about here.
For any doubt and issue you can comment in the comment section below. You can also post your own content here.
