In JavaScript, removing duplicate values from an array is a common operation that can be done using various techniques. Here are some of the most common ways to remove duplicate values from an array:
Option 1. Use for loop
You can use a loop along with a conditional statement.
let arr=[5,11,6,8,2,5];
let newArr = [];
for (i=0; i<arr.length; i++) {
if (!newArr.includes(arr[i])) {
newArr.push(arr[i]);
}
}
console.log(newArr); //[5,11,6,8,2]
We initialize an array arr with one duplicate value and a empty array called newArr that will hold the unique values. We use a for loop to iterate over each element in the input array.
Inside the loop, we check if the current element is already in the newArr array using the includes() method with ! which will return true or false on the condition. If the element is not found in the newArr array, then the condition will return true.
If the element is not found in the newArr array, we add it to the newArr array using the push() method. After iterating over all elements in the input array, we return the newArr array containing only unique values.
Option 2. Use a set
One of the simplest ways to remove duplicates from an array is to convert it into a Set object. A Set is a collection of unique values, so it automatically removes any duplicates when you convert the array to a Set. You can then convert the Set back to an array using the spread operator (…) or the Array.from() method
let arr=[5,11,6,8,2,5];
let newArr = [];
newArr = [...new Set(arr)];
console.log(newArr); //[5,11,6,8,2]
In this example, we create an array arr with some duplicate values. We then convert arr to a Set using the new Set() constructor and the spread operator (…). The resulting Set uniqueSet contains only unique values. Finally, we convert the Set back to an array newArr using the spread operator (…).
Option 3. Use filter
You can also remove duplicates from an array using the filter() method. The filter() method creates a new array with all elements that pass a certain test. You can use this method to filter out duplicate values by keeping only the first occurrence of each value.
let arr=[5,11,6,8,2,5];
let newArr = [];
newArr = arr.filter((e, i) => {
return arr.indexOf(e) === i;
});
console.log(newArr); //[5,11,6,8,2]
In this example above, we create an array arr with some duplicate values. We then use the filter() method to create a new array newArr that only contains the first occurrence of each value. The callback function passed to filter() checks if the index of the current value in the array is equal to the index of the first occurrence of that value. If it is, the value is kept in the filtered array.