Bug Tracker

Ticket #7927 (closed feature: worksforme)

Opened 4 years ago

Last modified 4 years ago

Array unique

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

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

comment:1 Changed 4 years ago by rwaldron

  • Status changed from new to closed
  • Resolution set to worksforme
  • Component changed from unfiled to core

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

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

comment:2 Changed 4 years ago by rwaldron

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 4 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 4 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 4 years ago by rwaldron

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.