remove duplicates from array in javascript

To remove duplicates from an array in JavaScript, there are several approaches. One straightforward way is to use a loop to iterate through the array and compare each element to the rest of the array to remove duplicates. However, this method can be time-consuming for long arrays.

A more efficient way to remove duplicates from an array is to use the Set object, introduced in ES6, which only stores unique values. We can convert the original array into a Set and then back into an array to remove duplicates. Here's how we can do it:

index.tsx
const arr = [1, 2, 2, 3, 3, 4, 5, 5];

const uniqueArr = Array.from(new Set(arr));

console.log(uniqueArr); // [1, 2, 3, 4, 5]
127 chars
6 lines

Alternatively, we can use the filter() method in combination with the indexOf() method to remove duplicates from the array. Here's an example:

index.tsx
const arr = [1, 2, 2, 3, 3, 4, 5, 5];

const uniqueArr = arr.filter((value, index, self) => {
  return self.indexOf(value) === index;
});

console.log(uniqueArr); // [1, 2, 3, 4, 5]
182 chars
8 lines

In this example, the filter() method creates a new array containing only the unique values of the original array. The indexOf() method is used to find the first occurrence of each value in the array, and the filter callback function only keeps the first occurrence of each value and removes the duplicates.

gistlibby LogSnag