How to retrieve distinct values from a JavaScript array (eliminate duplicates)

I have a numbers array that I need to ensure contains only distinct values. I came across the following code snippet online, which works well until it encounters a zero in the array. I also saw a different script that is quite similar but seems to handle this case without issue. Can someone explain what may be wrong with the prototype method I found?

Array.prototype.extractUnique = function() {
    let obj = {}, uniqueArray = [], index, element;
    for (index = 0; element = this[index]; index++) {obj[element] = true;}
    for (element in obj) {uniqueArray.push(element);}
    return uniqueArray;
}

The issue with your code lies in how JavaScript handles truthy and falsy values. In your loop, you’re using the condition element = this[index], which causes the loop to stop when it encounters a falsy value like zero. To fix this, you can modify the loop condition to check the index against the array’s length: index < this.length && (element = this[index]) !== undefined. This way, it ensures that all elements are considered, including zero, without terminating the loop prematurely. Another approach is using a Set, which is designed to store only unique values and can simplify your code: Array.from(new Set(this));.

You should also consider using the filter method. You can create a unique array by checking if the index of current element is same as the first index of that element in the array. It prevents duplicate values by ensuring their first occurrence is retained.