How do I remove duplicate elements from an array in JavaScript?
Benjamin C
benjamin c profile pic

To remove duplicate elements from an array in JavaScript, you can use various approaches depending on the requirements and characteristics of the array. Let's explore some common methods: 1. Using the Set object: The Set object is a built-in JavaScript object that allows you to store unique values of any type. You can convert an array to a Set, which automatically removes duplicates, and then convert it back to an array if needed.

1
2
3
4
5

   const array = [1, 2, 3, 3, 4, 5, 5];
   const uniqueArray = [...new Set(array)];
   console.log(uniqueArray); // Output: [1, 2, 3, 4, 5]
   

2. Using the filter() method: The filter() method creates a new array by filtering out elements that meet a specific condition. You can use it with indexOf() to only keep the first occurrence of each element.

1
2
3
4
5
6
7

   const array = [1, 2, 3, 3, 4, 5, 5];
   const uniqueArray = array.filter((value, index, self) => {
     return self.indexOf(value) === index;
   });
   console.log(uniqueArray); // Output: [1, 2, 3, 4, 5]
   

3. Using the reduce() method: The reduce() method applies a function to each element of an array, accumulating a single result. You can utilize it to build a new array by checking if an element already exists in the accumulator.

1
2
3
4
5
6
7
8
9
10

   const array = [1, 2, 3, 3, 4, 5, 5];
   const uniqueArray = array.reduce((accumulator, currentValue) => {
     if (!accumulator.includes(currentValue)) {
       accumulator.push(currentValue);
     }
     return accumulator;
   }, []);
   console.log(uniqueArray); // Output: [1, 2, 3, 4, 5]
   

4. Using ES6 Set and spread operator (alternative approach): In addition to the first method, you can also use the spread operator to convert the Set back to an array.

1
2
3
4
5

   const array = [1, 2, 3, 3, 4, 5, 5];
   const uniqueArray = Array.from(new Set(array));
   console.log(uniqueArray); // Output: [1, 2, 3, 4, 5]
   

These methods provide efficient ways to remove duplicate elements from an array in JavaScript. Depending on the complexity and size of the array, you can choose the most suitable approach for your specific needs.