You can remove duplicates in JavaScript using either the Set object or filtering logic.
✅ Solution 1 — Using Set (Simplest Way)
function getUniqueValues(arr) {
return [...new Set(arr)];
}
// Example:
console.log(getUniqueValues([1, 2, 2, 3, 4, 4, 5]));
Output:
[1, 2, 3, 4, 5]
🟢 Set automatically stores only unique values.
✅ Solution 2 — Using filter() and indexOf()
function getUniqueValues(arr) {
return arr.filter((value, index) => arr.indexOf(value) === index);
}
// Example:
console.log(getUniqueValues([1, 2, 2, 3, 4, 4, 5]));
Output:
[1, 2, 3, 4, 5]
🧩 Explanation:
indexOf(value)returns the first index where the value appears.- If the current index matches that first index → it’s unique (first occurrence).
🧠 In Short:
Use
[...new Set(arr)]to quickly get all unique numbers from an array.