Skip to main content

Bug Tracker

Side navigation

#7927 closed feature (worksforme)

Opened January 08, 2011 03:33PM UTC

Closed January 08, 2011 05:25PM UTC

Last modified January 08, 2011 08:09PM UTC

Array unique

Reported by: Michael Mior <michael.mior@gmail.com> 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.

#!js
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;
}
Attachments (0)
Change History (5)

Changed January 08, 2011 05:25PM UTC by rwaldron comment:1

component: unfiledcore
resolution: → worksforme
status: newclosed

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

http://jsfiddle.net/rwaldron/9Rwpn/

Changed January 08, 2011 05:41PM UTC by rwaldron comment:2

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.

Changed January 08, 2011 07:00PM UTC by Michael Mior <michael.mior@gmail.com> comment:3

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?

Changed January 08, 2011 07:47PM UTC by Michael Mior <michael.mior@gmail.com> comment:4

Also, the documentation says explicitly states, "Note that this only works on arrays of DOM elements, not strings or numbers." Why is that?

Changed January 08, 2011 08:09PM UTC by rwaldron comment:5

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.