Question
What are the best methods to get unique items from an array in JavaScript?
const array = [1, 2, 2, 3, 4, 4, 5];
const uniqueArray = [...new Set(array)]; // Output: [1, 2, 3, 4, 5]
Answer
Retrieving unique items from an array in JavaScript can be achieved using various techniques. This process is essential for data sanitization and helps enhance the quality of data processing in applications.
// Example using Set
const uniqueUsingSet = [...new Set(array)];
// Example using filter and indexOf
const uniqueUsingFilter = array.filter((item, index) => array.indexOf(item) === index);
// Example using reduce
const uniqueUsingReduce = array.reduce((accumulator, currentValue) => {
if (!accumulator.includes(currentValue)) {
accumulator.push(currentValue);
}
return accumulator;
}, []);
Causes
- Duplicate data can lead to errors in logic and calculations.
- Inconsistent data can affect user experience.
- Aggregating results or counting distinct values requires unique items.
Solutions
- Using the `Set` object, as it inherently stores only unique values.
- Employing the `filter()` method combined with `indexOf()` to eliminate duplicates.
- Utilizing `reduce()` to iteratively build an array of unique values.
Common Mistakes
Mistake: Using `indexOf()` alone to filter might not work correctly for complex data types (objects/arrays).
Solution: Make sure to stringify objects or use a specific unique property.
Mistake: Using a loop to check for duplicates without optimizations leads to performance issues with large datasets.
Solution: Consider using a `Set` which offers average O(1) time complexity for insertions.
Helpers
- unique items array JavaScript
- get unique values JavaScript
- JavaScript array deduplication
- Set object JavaScript
- filter method array unique values