How to Deduplicate an Array in JavaScript?

Estimated read time 1 min read

To deduplicate an array in JavaScript, you can use the Array.filter() method to keep only unique elements. Here’s an example:

const array = [1, 2, 3, 1, 2, 3];

const deduplicatedArray = array.filter((item, index) => array.indexOf(item) === index);

console.log(deduplicatedArray); // [1, 2, 3

In this example, the Array.filter() method loops over the elements of the array and returns only those elements for which array.indexOf(item) is equal to the current index. This means that only the first occurrence of each element will be kept.

You can also use the Set object to deduplicate an array:

const array = [1, 2, 3, 1, 2, 3];

const deduplicatedArray = [ Set(array)];

console.log(deduplicatedArray); // [1, 2, 3]

In this example, the Set object automatically removes duplicates, so you can convert it back to an array using the spread operator (...).

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply