How can I get a list of unique values in an array? Do I always have to use a second array or is there something similar to java's hashmap in JavaScript?
I am going to be using JavaScript and jQuery only. No additional libraries can be used.
How can I get a list of unique values in an array? Do I always have to use a second array or is there something similar to java's hashmap in JavaScript?
I am going to be using JavaScript and jQuery only. No additional libraries can be used.
ES6 way:
One Liner, Pure JavaScript
With ES6 syntax
list = list.filter((x, i, a) => a.indexOf(x) == i)
With ES5 syntax
Browser Compatibility: IE9+
Since I went on about it in the comments for @Rocket's answer, I may as well provide an example that uses no libraries. This requires two new prototype functions,
contains
andunique
You can then do:
For more reliability, you can replace
contains
with MDN'sindexOf
shim and check if each element'sindexOf
is equal to -1: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/indexOfIf you want to leave the original array intact,
you need a second array to contain the uniqe elements of the first-
Most browsers have
Array.prototype.filter
:Another thought of this question. Here is what I did to achieve this with fewer code.