javascript tutorial - [Solved-5 Solutions] Unique values in an array - javascript - java script - javascript array
Problem:
We have an array of numbers that we need to make sure are unique. We found the code snippet below on the internet and it works great until the array has a zero in it. We found this other script here on SO that looks almost exactly like it, but it doesn't fail. So for the sake of helping me learn, can someone help me determine where the prototype script is going wrong ?
Solution 1:
With JavaScript 1.6 / ECMAScript 5 we can use the native filter method of an Array in the following way to get an array with unique values:
The native method filter will loop through the array and leave only those entries that pass the given callback function onlyUnique.
onlyUnique checks, if the given value is the first occurring. If not, it must be a duplicate and will not be copied. This solution works without any extra library like jQuery or prototype.js.
It works for arrays with mixed value types too.
For old Browsers (<ie9), that do not support the native methods filter and indexOf we can find work arounds in the MDN documentation for filter and indexOf . If we want to keep the last occurrence of a value, simple replace indexOf by lastIndexOf. With ES6 it could be shorten to this:
ES6 has a native object Set to store unique values. To get an array with unique values we could do now this:
The constructor of Set takes an iterable object, like Array, and the spread operator ... transform the set back into an Array.
Solution 2:
Updated answer for ES6/ES2015: Using the Set operator, the single line solution is:
Which returns
This can also be shortened using spread operator , like
Solution 3:
We can also use underscore.js .
Run code snippet Expand snippet which will return:
Solution 4:
We have since found a nice method that uses jQuery
Solution 5:
This prototype getUnique
is not totally correct, because if we have a Array like: ["1",1,2,3,4,1,"foo"]
it will return ["1","2","3","4"]
and "1"
using:
The above will produce ["1",2,3,4,1,"foo"]
.