How can I convert an array to a unique array in JavaScript?
Ava W
ava w profile pic

To convert an array to a unique array in JavaScript, you can use various approaches. Here are a few different methods to achieve this: 1. Using theSet object: TheSet object is a built-in JavaScript object that allows you to store unique values of any type. You can convert an array to aSet and then convert it back to an array to remove duplicates.

1
2
3
4
5

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

In this example, theSet object removes duplicate values, andArray.from() is used to convert theSet back to an array. 2. Using thefilter() method: You can use thefilter() method to create a new array that contains only unique values by checking if the current element's index is equal to the first occurrence of that element in the array.

1
2
3
4
5

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

Thefilter() method iterates over each element and keeps only the elements whose index is equal to the index of the first occurrence of that element. 3. Using thereduce() method: Thereduce() method can also be used to build a new array by checking if the current element already exists in the accumulator array.

1
2
3
4
5
6
7
8
9
10

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

Thereduce() method accumulates the unique elements by checking if the element is already present in the accumulator array. All these methods provide different ways to convert an array to a unique array in JavaScript. Choose the one that suits your needs and the specific requirements of your code.