How do I remove duplicates from an array in JavaScript?
Ava W
ava w profile pic

In JavaScript, there are multiple approaches to remove duplicates from an array. Here are a few common methods: 1. Using theSet object: - TheSet object is a built-in JavaScript object that allows you to store unique values. By converting the array to aSet and then back to an array, you automatically remove any duplicate elements.

1
2
3
4

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

In this example,Array.from(new Set(array)) creates a newSet from the arrayarray, which automatically removes duplicates. Then,Array.from() is used to convert theSet back to an array. 2. Using thefilter() method: - Thefilter() method allows you to create a new array that includes only elements that pass a certain condition. By filtering out elements based on their index, you can effectively remove duplicates.

1
2
3
4

   const array = [1, 2, 3, 2, 4, 1, 5];
   const uniqueArray = array.filter((value, index, self) => self.indexOf(value) === index);
   

Here,array.filter() creates a new array by iterating over each element of the original array and applying the filter condition. The condition(value, index, self) => self.indexOf(value) === index ensures that only the first occurrence of each element is kept in the resulting array. 3. Using thereduce() method: - Thereduce() method allows you to iteratively process the elements of an array and accumulate a result. By checking if an element already exists in the accumulator array, you can exclude duplicates.

1
2
3
4
5
6
7
8
9

   const array = [1, 2, 3, 2, 4, 1, 5];
   const uniqueArray = array.reduce((accumulator, value) => {
     if (!accumulator.includes(value)) {
       accumulator.push(value);
     }
     return accumulator;
   }, []);
   

In this example,array.reduce() processes each element of the original array,accumulator keeps track of the unique elements found so far, and the condition!accumulator.includes(value) ensures that only non-duplicate elements are added toaccumulator. 4. Using ES6 syntax andindexOf() method: - You can use ES6 features, such as the spread operator (...) and theindexOf() method, to create a new array that excludes duplicates.

1
2
3
4

   const array = [1, 2, 3, 2, 4, 1, 5];
   const uniqueArray = [...new Set(array)];
   

Here,[...new Set(array)] creates aSet from the array, which removes duplicates, and the spread operator... converts theSet back to an array. Choose the method that best suits your requirements and the version of JavaScript you are using. TheSet approach is widely supported in modern JavaScript environments and provides a concise solution. Thefilter(),reduce(), and ES6 syntax approaches are also effective alternatives, especially in scenarios where you need more control over the process or are targeting older JavaScript environments.