Home >Web Front-end >JS Tutorial >How to Efficiently Retrieve Unique Values from a JavaScript Array, Including Zeroes?
Retrieve Unique Values from a JavaScript Array
In this question, we aim to eliminate duplicate values from a JavaScript array while ensuring the integrity of zero elements. Let's examine a snippet that encounters an issue when handling zeroes:
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; };
This snippet leverages JavaScript's inherent coercion, where values are implicitly converted to truthy or falsy values. Zero is a falsy value in JavaScript, and since objects in JavaScript are truthy by default, it gets added to the object during the initial loop. Consequently, it is then pushed into the resulting array during the subsequent loop.
However, in modern JavaScript (ES5 and later), we have access to more efficient and reliable methods for achieving uniqueness in arrays:
Native Filter Method:
The filter method allows us to iterate over the elements of an array and return a new array containing only the elements that pass a specified test function. We can define a function that checks if an element is unique within the array by comparing its index with the first occurrence of the same element:
function onlyUnique(value, index, array) { return array.indexOf(value) === index; } // Example usage: const a = ['a', 1, 'a', 2, '1']; const unique = a.filter(onlyUnique); console.log(unique); // Logs: ['a', 1, 2, '1']
The above is the detailed content of How to Efficiently Retrieve Unique Values from a JavaScript Array, Including Zeroes?. For more information, please follow other related articles on the PHP Chinese website!