Introduction
When working with JavaScript, arrays are one of the most common data structures you’ll encounter. Often you need to get unique values from array to eliminate duplicates, prepare data for display, or perform further calculations. This article explains several reliable techniques to achieve that goal, provides clear step‑by‑step examples, and highlights performance tips so you can choose the best approach for any situation It's one of those things that adds up..
Understanding Arrays in JavaScript
What is an Array?
An array is an ordered collection of elements that can hold any type of value—numbers, strings, objects, or even other arrays. Each element has a numeric index starting from 0, and you can access, modify, or iterate over them using built‑in methods.
Why Remove Duplicates?
Duplicates can cause bugs in logic that expects distinct items, inflate counts in reports, or produce incorrect UI lists. Ensuring each value appears only once improves reliability and readability.
Methods to Get Unique Values
Below are the most widely used techniques, each with its own advantages and trade‑offs.
Using Set (ES6)
The Set object stores only unique values, making it the simplest way to get unique values from array.
const numbers = [1, 2, 3, 2, 4, 1, 5];
const unique = [...new Set(numbers)];
console.log(unique); // [1, 2, 3, 4, 5]
Steps
- Create a new Set from the original array:
new Set(array). - Spread the Set back into a regular array:
[...set].
Pros
- O(n) time complexity – each element is processed once.
- Very concise and readable.
Cons
- Does not preserve the original order in older browsers (though modern engines maintain insertion order).
Using filter with indexOf
This approach filters out duplicates by checking the first occurrence of each element.
const strings = ['apple', 'banana', 'apple', 'cherry', 'banana'];
const unique = strings.filter((item, index) => strings.indexOf(item) === index);
console.log(unique); // ['apple', 'banana', 'cherry']
Steps
- Iterate over the array with
filter. - Compare the current index with
indexOf(item). If they match, the element is the first occurrence.
Pros
- Works in all JavaScript environments.
Cons
- O(n²) time because
indexOfscans the array for each element, which can be slow for large arrays.
Using reduce
reduce lets you build a new array while checking for duplicates on the fly.
const values = [10, 20, 10, 30, 20, 40];
const unique = values.reduce((acc, cur) => {
if (!acc.includes(cur)) {
acc.push(cur);
}
return acc;
}, []);
console.log(unique); // [10, 20, 30, 40]
Steps
- Initialize an empty array as the accumulator.
- For each element, add it to the accumulator only if it isn’t already present (
includes).
Pros
- Gives you full control over the construction process.
Cons
- Still O(n²) due to
includes, which can be inefficient for big data sets.
Using a Manual Loop with a Set
If you need more flexibility (e.g., custom comparison logic), a manual loop can be combined with a Set Still holds up..
function getUnique(arr, comparator = (a, b) => a === b) {
const seen = new Set();
const result = [];
for (const item of arr) {
if (!seen.has(item)) {
seen.add(item);
result.
const data = [{id: 1}, {id: 2}, {id: 1}];
const uniqueObjects = getUnique(data, (a, b) => a.Day to day, id === b. id);
console.
*Steps*
1. Create a **Set** to track items you’ve already encountered.
2. Loop through the array, adding each new item to the result only if it isn’t in the **Set**.
*Pros*
- **O(n)** performance thanks to the **Set**.
- Allows custom equality checks via the comparator function.
*Cons*
- Slightly more code, but still easy to understand.
## Performance Considerations
When you **get unique values from array**, performance matters, especially with large data sets.
| Method | Time Complexity | Space Complexity | Browser Compatibility |
|-----------------------|-----------------|------------------|-----------------------|
| **Set** | O(n) | O(n) | ES6+ (modern browsers) |
| **filter + indexOf** | O(n²) | O(n) | All |
| **reduce + includes**| O(n²) | O(n) | All |
| **Manual Loop + Set**| O(n) | O(n) | All |
For most applications, the **Set** approach is the fastest and cleanest. If you must support very old browsers that lack **Set**, consider the manual loop with a **Set** polyfill or a library that provides a similar utility.
## Practical Examples
### Removing Duplicate IDs from a List
```javascript
const userIds = [101, 202, 303, 202, 404, 101];
const uniqueIds = [...new Set(userIds)];
// Use uniqueIds for reporting or UI rendering
Preparing a List of Unique Tags
const tags = ['js', 'node', 'js', 'react', 'node', 'vue'];
const uniqueTags = tags.filter((tag, i) => tags.indexOf(tag) === i);
// ['js', 'node', 'react', 'vue']
Deduplicating Objects by a Specific Property
const items = [
{ name: 'apple', color: 'red' },
{ name: 'banana', color: 'yellow' },
{ name: 'apple', color: 'green' }
];
const uniqueByName = items.filter((item, index) =>
items.findIndex(i => i.That said, name === item. name) === index
);
console.
## FAQ
**Q1: Can I get unique values without creating a new array?**
A: The **Set** object itself is a collection of unique values, but if you need a plain JavaScript array (e.g., for methods like `map` or `forEach`), you must convert it using the spread operator (`[...set]`) or `Array.from(set)`.
**Q2: Does the order of elements change when using **Set**?**
A: Modern JavaScript engines preserve the insertion order of elements in a **Set**, so the resulting array will keep the original order of first occurrences.
**Q3: What if my array contains `NaN` values?**
A: `Set` treats `NaN` as a distinct value, so duplicates of `NaN` will not be removed. The `filter`/`indexOf` method also fails to recognize `NaN` as equal to itself, so you’ll need a custom comparison for `NaN` handling.
**Q4: Is there a built‑in method that works on both arrays and strings?**
A: Not directly. On the flip side, you can convert a string to an array of characters, apply any of the techniques above, and then join the characters back into a string if needed.
**Q5: How does memory usage compare among the methods?**
A: All methods that create a new array (Set, filter, reduce, manual loop) require additional memory proportional to the number of unique elements. The **Set** approach is memory‑efficient because it stores each unique value only once internally.
## Conclusion
Getting unique values from an array is a fundamental task in JavaScript development. The **Set** constructor offers the cleanest, fastest solution for most modern projects, while the `filter` with `indexOf`, `reduce`, and manual loop techniques provide fallback options for older environments or custom comparison logic. Understanding the time‑complexity differences helps you choose the right tool, ensuring your code remains performant and maintainable. By applying the methods described here, you can confidently **get unique values from array** in any JavaScript scenario.