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 ?
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.
Updated answer for ES6/ES2015: Using the Set operator, the single line solution is:
This can also be shortened using spread operator , like
We can also use underscore.js .
Run code snippet Expand snippet which will return:
We have since found a nice method that uses jQuery
getUnique is not totally correct, because if we have a Array like:
["1",1,2,3,4,1,"foo"] it will return
The above will produce