jQuery.unique on an array of strings
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)
Update:
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 :
- use
$.grep
instead ofArray.filter
- use
$.inArray
instead ofArray.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)
I know unique works with DOM but this WORKS on arrays of int:
$.unique(arr.sort());
It might work on an array strings, etc, but it has not been designed for that use...
Notice that the code for unique()
is hiding in Sizzle as uniqueSort
: github source
While some of that extra code might seem like it would work on any array, pay close attention to sortOrder
as defined here. It does a lot of extra work to put things in "document order" - hence why the documentation states that it should only be used on arrays of DOM elements.
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.