#7927 closed feature (worksforme)
Array unique
Reported by: | Owned by: | ||
---|---|---|---|
Priority: | undecided | Milestone: | 1.next |
Component: | core | Version: | 1.4.4 |
Keywords: | Cc: | ||
Blocked by: | Blocking: |
Description
Why isn't there a function in jQuery like unique()
, but for arrays? The function below is pulled from http://www.devcurry.com/2010/04/remove-duplicate-elements-from-array.html. Feel free to correct me if this is outside the scope of jQuery.
Array.prototype.unique = function () { var arrVal = this; var uniqueArr = []; for (var i = arrVal.length; i--; ) { var val = arrVal[i]; if ($.inArray(val, uniqueArr) === -1) { uniqueArr.unshift(val); } } return uniqueArr; }
Change History (5)
comment:1 Changed 12 years ago by
Component: | unfiled → core |
---|---|
Resolution: | → worksforme |
Status: | new → closed |
comment:2 Changed 12 years ago by
One thing to keep in mind, since jQuery.unique() is intended to be used with array's of elements, it returns them in document order, which means normal arrays will be backwards.
Additionally, jQuery will not extend native/host objects, prototypes or constructors.
comment:3 Changed 12 years ago by
Thanks for the rapid response (as well as the brief demo of jsFiddle usage). Re: your comment about backwards arrays, does this mean that I should reverse arrays after calling unique
if I want them in the original order?
comment:4 Changed 12 years ago by
Also, the documentation says explicitly states, "Note that this only works on arrays of DOM elements, not strings or numbers." Why is that?
comment:5 Changed 12 years ago by
Well, as you can see its a pain to have to reverse the array... Not sure why I didn't mention this previously, but for excellent implementations of functional utilities, I ALWAYS use Underscore.js
Example: http://jsfiddle.net/rwaldron/3ShLf/1/
Underscore is an awesome friend of jQuery.
Thanks for taking the time to contribute to the jQuery Project. jQuery already supports an array unique implementation:
http://jsfiddle.net/rwaldron/9Rwpn/