Finding and removing duplicates in a JavaScript array can be achieved using various methods. In this blog post, we will explore two common approaches: using the Set data structure and sorting the array.
Using the Set Data Structure
To remove duplicates from an array, you can utilize the Set data structure offered by JavaScript. This can be done in just one line of code:
const yourArrayWithoutDuplicates = [...new Set(yourArray)];
By spreading the Set object into an array, you can obtain a new array without any duplicate elements.
To identify which elements are duplicates, you can use the “array without duplicates” obtained above and remove each item it contains from the original array. Here’s an example:
const yourArray = [1, 1, 2, 3, 4, 5, 5];
const yourArrayWithoutDuplicates = [...new Set(yourArray)];
let duplicates = [...yourArray];
yourArrayWithoutDuplicates.forEach((item) => {
const i = duplicates.indexOf(item);
duplicates = duplicates.slice(0, i).concat(duplicates.slice(i + 1, duplicates.length));
});
console.log(duplicates); // [1, 5]
Sorting the Array
Another method to find duplicates is by sorting the array and comparing each element with the next one. If they are the same, you can add it to a new array. Here’s an example:
const yourArray = [1, 1, 2, 3, 4, 5, 5];
let duplicates = [];
const tempArray = [...yourArray].sort();
for (let i = 0; i < tempArray.length; i++) {
if (tempArray[i + 1] === tempArray[i]) {
duplicates.push(tempArray[i]);
}
}
console.log(duplicates); // [1, 5]
Keep in mind that the sorting method works only for primitive values and not objects. If you are dealing with objects, you will need to implement a custom comparison function.
Tags: JavaScript, array, duplicates, Set, sorting