Bug Tracker

Opened 10 years ago

Closed 10 years ago

Last modified 10 years ago

#7927 closed feature (worksforme)

Array unique

Reported by: Michael Mior <michael.mior@…> Owned by:
Priority: undecided Milestone: 1.next
Component: core Version: 1.4.4
Keywords: Cc:
Blocked by: Blocking:


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) {
  return uniqueArr;

Change History (5)

comment:1 Changed 10 years ago by Rick Waldron

Component: unfiledcore
Resolution: worksforme
Status: newclosed

Thanks for taking the time to contribute to the jQuery Project. jQuery already supports an array unique implementation:


comment:2 Changed 10 years ago by Rick Waldron

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 10 years ago by Michael Mior <michael.mior@…>

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 10 years ago by Michael Mior <michael.mior@…>

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 10 years ago by Rick Waldron

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.

Note: See TracTickets for help on using tickets.