JavaScript array deduplication: get all unique values
P粉779565855
2023-08-20 11:36:41
<pre class="brush:php;toolbar:false;"><p>I have an array of numbers and I need to make sure the numbers in it are unique. I found the following code snippet on the internet which works fine until there is a zero in the array. I found another almost identical script on Stack Overflow, but it doesn't fail. </p>
<p>To help me learn, can anyone help me identify what's wrong with the prototype script? </p>
<pre><code>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;
}</code></pre>
<code>
<h3>More answers from duplicate questions: </h3>
<ul>
<li>Remove duplicate values from JS array</li>
</ul>
<h3>Similar questions: </h3>
<ul>
<li>Get all non-unique values in the array (ie: repeated/multiple occurrences)</li>
</ul><p><br /></p></code></pre>
Updated answer for ES6/ES2015: One-line solution using Set and spread operator (thanks le-m) as follows:
The return result is:
With JavaScript 1.6 / ECMAScript 5, you can use the array's native
filter
method to get an array with unique values :