Remove Duplicates array values in javascript
hljs.initHighlightingOnLoad();
Removing Duplicate Array Values in Javascript
As a web developer, I have often come across situations where I needed to remove duplicate values from an array in Javascript. There are multiple ways to achieve this, and I'll discuss some of them below:
Using Set
The easiest and most efficient way to remove duplicate values from an array is by using the Set object in Javascript. Here's how you can do it:
let arr = [1, 2, 2, 3, 4, 4, 5];
let uniqueArr = [...new Set(arr)];
console.log(uniqueArr); // Output: [1, 2, 3, 4, 5]
Using a For Loop
You can also remove duplicates from an array by looping through it and checking each value against the rest of the values in the array. Here's an example:
let arr = [1, 2, 2, 3, 4, 4, 5];
let uniqueArr = [];
for (let i = 0; i < arr.length; i++) {
if (uniqueArr.indexOf(arr[i]) === -1) {
uniqueArr.push(arr[i]);
}
}
console.log(uniqueArr); // Output: [1, 2, 3, 4, 5]
Using the Filter Method
You can also use the filter method to remove duplicates from an array. Here's how:
let arr = [1, 2, 2, 3, 4, 4, 5];
let uniqueArr = arr.filter((value, index, self) => {
return self.indexOf(value) === index;
});
console.log(uniqueArr); // Output: [1, 2, 3, 4, 5]
Conclusion
Removing duplicate values from an array is a common problem in Javascript programming. You can use the Set object, a for loop or the filter method to achieve this. The choice of method depends on your preferences and the specific situation you're dealing with.