0

I am trying to apply the jQuery $.unique() function to an array of objects. I enjoy using this function with an array of primative variables but apparently it doesn't work with objects, as seen here: http://jsfiddle.net/abs10gxo/

var arr1 = [ 
    "aaa",
    "bbb",
    "aaa" 
];

console.log($.unique(arr1));  // Works as expected.

var arr2 = [ 
    { "a": "aaa" }, 
    { "b": "bbb" }, 
    { "a": "aaa" } 
];

console.log($.unique(arr2));  // Doesn't work as expected.

I can't seem to find any literature on jQuery.com in regard to using this function with an array of objects; it only adheres to primative types. Can anyone recommend a solution? Library or custom are both welcome answers. I am familiar with doing this in C++ where you can overload the comparative == sign operator but not sure if that is the best approach since I am using jQuery.

Jim22150
  • 511
  • 2
  • 8
  • 22
  • does this help http://stackoverflow.com/questions/15125920/how-to-get-distinct-values-from-an-array-of-objects-in-javascript ? – Dhiraj Jun 24 '15 at 15:46
  • Thanks. There are some tricks in there I have thought of but I was hoping there was a simple jQuery function I wasn't aware of that could be as short as the $.unique() function. – Jim22150 Jun 24 '15 at 15:50
  • As the post mentioned by Dhiraj makes quite clear, when you compare objects *you* have to decide *what* makes them *identical*. Therefore you will have to define your own comparison function at some point. The two `{"a":"aaa"}` objects will appear to be different for JavaScript as they *are* separate objects, albeit with "similar" contents. – Carsten Massmann Jun 24 '15 at 15:56

0 Answers0