The description of jQuery.unique() states:
Sorts an array of DOM elements, in place, with the duplicates removed. Note that this only works on arrays
Although it works, you should probably take into consideration the function description. If the creators say that it is not designed for filtering arrays of anything else than dom elements, you should probably listen to them.
Besides, this functionality is quite easy to be reproduced :
function unique(array){
return array.filter(function(el, index, arr) {
return index === arr.indexOf(el);
});
}
(demo page)
In order for this code to work in all browsers (including ie7 that doesn't support some array features - such as indexOf
or filter
), here's a rewrite using jquery functionalities :
Array.filter
Array.indexOf
Now here's how the translated code should look like:
function unique(array) {
return $.grep(array, function(el, index) {
return index === $.inArray(el, array);
});
}
(demo page)
$.unique
will remove duplicate DOM elements, not identical DOM elements. When you try to use it on strings, you get unpredictable behavior and the sorting will (probably) fail.
It's a function intended for internal use by jQuery only, and won't be useful to mere mortals like you and I.
There's a quick way to extend the jQuery.unique() function to work on arrays containing elements of any type.
(function($){
var _old = $.unique;
$.unique = function(arr){
// do the default behavior only if we got an array of elements
if (!!arr[0].nodeType){
return _old.apply(this,arguments);
} else {
// reduce the array to contain no dupes via grep/inArray
return $.grep(arr,function(v,k){
return $.inArray(v,arr) === k;
});
}
};
})(jQuery);
// in use..
var arr = ['first',7,true,2,7,true,'last','last'];
$.unique(arr); // ["first", 7, true, 2, "last"]
var arr = [1,2,3,4,5,4,3,2,1];
$.unique(arr); // [1, 2, 3, 4, 5]
http://www.paulirish.com/2010/duck-punching-with-jquery/ - example #2
I know unique works with DOM but this WORKS on arrays of int:
$.unique(arr.sort());
$.unique will only remove duplicate DOM element, if you need it for array :
var result=[] ;
$.each([12,1,2,4,3,1,4,3,3,2,111],
function(i,e){ if($.inArray(e,result)===-1) result.push(e) ;});
result;
If not limited using jQuery, consider to use Set from ES6.
var arr = ['foo', 'bar', 'bar'];
Array.from(new Set(arr)); // #=> ["foo", "bar"]
Working for Firefox 45, Safari 9 and Chrome 49.