jQuery.unique lets you get unique elements of an array, but the docs say the function is mostly for internal use and only operates on DOM elements. Another SO response said the unique()
function worked on numbers, but that this use case is not necessarily future proof because it's not explicitly stated in the docs.
Given this, is there a "standard" jQuery function for accessing only the unique values — specifically, primitives like integers — in an array? (Obviously, we can construct a loop with the each()
function, but we are new to jQuery and would like to know if there is a dedicated jQuery function for this.)
You can use
array.filter
to return the first item of each distinct value-If supporting IE8 and below is primary, don't use the unsupported
filter
method.Otherwise,
And for dom elements there is no example is needed here I guess because you already know that!
Here is the jsfiddle link of live example: http://jsfiddle.net/3BtMc/4/
Paul Irish has a "Duck Punching" method (see example 2) that modifies jQuery's
$.unique()
method to return unique elements of any type:Walk the array and push items into a hash as you come across them. Cross-reference the hash for each new element.
Note that this will ONLY work properly for primitives (strings, numbers, null, undefined, NaN) and a few objects that serialize to the same thing (functions, strings, dates, possibly arrays depending on content). Hashes in this will collide as they all serialize to the same thing, e.g. "[object Object]"
There's also no reason you can't use jQuery.unique. The only thing I don't like about it is that it destroys the ordering of your array. Here's the exact code for it if you're interested:
I would use underscore.js, which provides a
uniq
method that does what you want.