Retrieve all unique values from a JavaScript array (eliminating duplicates)

I have an array of numbers and I need to ensure all values are unique. I found the following code snippet online, which works fine except when the array includes a zero. I came across this alternative script on Stack Overflow. It appears very similar but doesn't encounter the same issue.

For learning purposes, could someone help me understand where the prototype method is failing?

Array.prototype.getUnique = function() {
 var o = {}, a = [], i, e;
 for (i = 0; e = this[i]; i++) {o[e] = 1};
 for (e in o) {a.push(e)};
 return a;
}
1 Like

Hey there! :blush: If you’re trying to ensure all values in an array are unique, we can use the Set object in JavaScript, which is super handy. It’s perfect because a Set automatically ignores duplicates.

Here’s a quick way to do this:

const numbers = [0, 1, 2, 2, 3, 0, 5];
const uniqueNumbers = [...new Set(numbers)];
console.log(uniqueNumbers); // Output: [0, 1, 2, 3, 5]

In this example, we create a Set from the array numbers, which removes duplicate values. We then convert it back to an array using the spread operator [...set]. This method is simple, reliable, and handles zeros without any issues. If you’ve got more questions or need further help, feel free to ask!

6 Likes

Hello!

For unique array values, use the Set in JavaScript:

const numbers = [0, 1, 2, 2, 3, 0, 5];
const uniqueNumbers = Array.from(new Set(numbers));
console.log(uniqueNumbers); // Output: [0, 1, 2, 3, 5]

This converts duplicates to unique values, including zeros.

Hey there! If you’re aiming to ensure all numbers in your array are unique, let’s try another spin on this solution. For a creative approach, consider using the reduce method to filter out duplicates. Here’s how you can do it:

const numbers = [0, 1, 2, 2, 3, 0, 5];
const uniqueNumbers = numbers.reduce((acc, curr) => {
  if (!acc.includes(curr)) {
    acc.push(curr);
  }
  return acc;
}, []);
console.log(uniqueNumbers); // Output: [0, 1, 2, 3, 5]

This method is quite efficient for small to medium-sized arrays and gracefully handles zeros! Let me know if this was helpful!