How to Remove Duplicate Values From a Javascript Array?
There are several ways to remove duplicate values from a JavaScript array. Here are a few approaches:
- Using a Set: The simplest way to remove duplicates is by converting the array into a Set, and then back into an array. Here's the code:
const myArray = [1, 2, 2, 3, 3, 4, 5];
const uniqueArray = [...new Set(myArray)];
console.log(uniqueArray); // Output: [1, 2, 3, 4, 5]
- Using a loop: You can also use a loop to iterate through the array and check for duplicates. Here's an example:
const myArray = [1, 2, 2, 3, 3, 4, 5];
const uniqueArray = [];
for (let i = 0; i < myArray.length; i++) {
if (uniqueArray.indexOf(myArray[i]) === -1) {
uniqueArray.push(myArray[i]);
}
}
console.log(uniqueArray); // Output: [1, 2, 3, 4, 5]
- Using a filter method: The filter method creates a new array with all elements that pass the test implemented by the provided function. Here's how you can use it to remove duplicates:
const myArray = [1, 2, 2, 3, 3, 4, 5];
const uniqueArray = myArray.filter((item, index) => {
return myArray.indexOf(item) === index;
});
console.log(uniqueArray); // Output: [1, 2, 3, 4, 5]
There are many other ways to remove duplicates from an array, but these are some of the most common and straightforward approaches.