How to Remove Duplicate Values From a Javascript Array?

javascript

There are several ways to remove duplicate values from a JavaScript array. Here are a few approaches:

  1. 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]
  1. 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]
  1. 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.

Latest Questions

javascript How to Check if a Javascript Array Includes a Given Value? javascript How to Completely Uninstall Nodejs, and Reinstall From Scratch on Mac OS X? javascript How to Map Values of a Javascript Object to a New Object Using a Function?