In JavaScript, it’s common to encounter scenarios where you need to filter out duplicate values from an array to obtain a list of unique elements. There are several approaches to achieve this, each with its own advantages and use cases. In this article, we will explore different methods to get all unique values in a JavaScript array, providing detailed descriptions and complete code examples for each approach.
Approach 1. Using a Set
The Set object lets you store unique values of any type, whether primitive values or object references. This is one of the most efficient ways to get unique values 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 keep 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.