Removing Duplicates from an Array in JavaScript: Various Methods
23 views
Sure, in JavaScript, you can remove duplicates from an array using various methods. Here are some of the most common and efficient ways to do this:
Using a Set
The Set object lets you store unique values of any type. By converting an array to a Set and then back to an array, you can easily remove duplicates.
const removeDuplicates = (arr) => {
return [...new Set(arr)];
};
// Example usage
const arr = [1, 2, 3, 1, 2, 4];
const uniqueArr = removeDuplicates(arr);
console.log(uniqueArr); // Output: [1, 2, 3, 4]
Using filter and indexOf
You can also use the filter method in combination with indexOf to remove duplicates.
const removeDuplicates = (arr) => {
return arr.filter((item, index) => arr.indexOf(item) === index);
};
// Example usage
const arr = [1, 2, 3, 1, 2, 4];
const uniqueArr = removeDuplicates(arr);
console.log(uniqueArr); // Output: [1, 2, 3, 4]
Using reduce
Another way to remove duplicates is by utilizing the reduce method.
const removeDuplicates = (arr) => {
return arr.reduce((acc, item) => {
if (!acc.includes(item)) {
acc.push(item);
}
return acc;
}, []);
};
// Example usage
const arr = [1, 2, 3, 1, 2, 4];
const uniqueArr = removeDuplicates(arr);
console.log(uniqueArr); // Output: [1, 2, 3, 4]
Using a forEach loop and an object for tracking
You can use a forEach loop along with an object to track and remove duplicates.
const removeDuplicates = (arr) => {
const seen = {};
const uniqueArr = [];
arr.forEach(item => {
if (!seen[item]) {
seen[item] = true;
uniqueArr.push(item);
}
});
return uniqueArr;
};
// Example usage
const arr = [1, 2, 3, 1, 2, 4];
const uniqueArr = removeDuplicates(arr);
console.log(uniqueArr); // Output: [1, 2, 3, 4]
Each of these methods has its own advantages, so you can choose the one that fits your needs best. Using Set is generally the most concise and efficient for basic types like numbers and strings.