In JavaScript, working with arrays often involves managing and manipulating data, including removing duplicate values. There are several ways to achieve this, each with its own advantages and use cases. This article explores different methods to remove duplicate values from an array in JavaScript, providing detailed descriptions and complete code examples for each approach.
Approach 1. Using Set
The Set object lets you store unique values of any type, whether primitive values or object references. This is one of the simplest and most efficient methods to remove duplicates from an array.
Example
let array = [1, 2, 2, 3, 4, 4, 5]; let uniqueArray = [...new Set(array)]; console.log(uniqueArray); // Output: [1, 2, 3, 4, 5]
Explanation
- new Set(array): Creates a new Set object from the array, automatically removing duplicate values.
- […new Set(array)]: Uses the spread operator (…) to convert the Set back into an array.
Approach 2. Using filter() and indexOf() Methods
You can use the filter() method in combination with indexOf() to retain only the first occurrence of each element in the array.
Example
let array = [1, 2, 2, 3, 4, 4, 5]; let uniqueArray = array.filter( (value, index) => array.indexOf(value) === index); console.log(uniqueArray); // Output: [1, 2, 3, 4, 5]
Explanation
- array.filter((value, index) => array.indexOf(value) === index): Filters the array to include only elements whose first occurrence index matches the current index.
Approach 3. Using reduce() Method
The reduce() method can be used to accumulate unique values into a new array.
Example
let array = [1, 2, 2, 3, 4, 4, 5]; let uniqueArray = array.reduce((acc, value) => { if (!acc.includes(value)) { acc.push(value); } return acc; }, []); console.log(uniqueArray); // Output: [1, 2, 3, 4, 5]
Explanation
- array.reduce((acc, value) => {…}, []): Reduces the array by accumulating values into acc (an initially empty array) if they are not already included.
Approach 4. Using forEach() and an Object
This approach uses a plain object to track the occurrence of each element and then collects the unique values.
Example
let array = [1, 2, 2, 3, 4, 4, 5]; let uniqueArray = []; let seen = {}; array.forEach((value) => { if (!seen[value]) { uniqueArray.push(value); seen[value] = true; } }); console.log(uniqueArray); // Output: [1, 2, 3, 4, 5]
Explanation
- seen[value] = true: Marks the value as seen.
- if (!seen[value]): Checks if the value has not been seen before pushing it to uniqueArray.
Approach 5. Using Map() Method
The Map object can also be utilized to ensure the uniqueness of values.
Example
let array = [1, 2, 2, 3, 4, 4, 5]; let map = new Map(); array.forEach((value) => { map.set(value, true); }); let uniqueArray = [...map.keys()]; console.log(uniqueArray); // Output: [1, 2, 3, 4, 5]
Explanation
- map.set(value, true): Adds the value to the map.
- […map.keys()]: Converts the map keys (unique values) back into an array.