Sai Krishna Deep Sai Krishna Deep - 1 month ago 8
jQuery Question

How to get Unique Array whose elemets are Objects using Javascript

Below is an examplle of an array I have

var mm = [
{"id":"Junk","text":"Junk","parent":"#"},
{"id":"IMG_0245.JPG","text":"IMG_0245.JPG","parent":"Junk"},
{"id":"Junk","text":"Junk","parent":"#"},
{"id":"IMG_0246.JPG","text":"IMG_0246.JPG","parent":"Junk"},
{"id":"Junk","text":"Junk","parent":"#"},
{"id":"IMG_0247.JPG","text":"IMG_0247.JPG","parent":"Junk"},
{"id":"Junk","text":"Junk","parent":"#"},
{"id":"IMG_0248.JPG","text":"IMG_0248.JPG","parent":"Junk"},
{"id":"Junk","text":"Junk","parent":"#"},
{"id":"IMG_0249.JPG","text":"IMG_0249.JPG","parent":"Junk"},
{"id":"Junk","text":"Junk","parent":"#"},
{"id":"IMG_0250.JPG","text":"IMG_0250.JPG","parent":"Junk"},
{"id":"Junk","text":"Junk","parent":"#"},
{"id":"IMG_0251.JPG","text":"IMG_0251.JPG","parent":"Junk"},
{"id":"Junk","text":"Junk","parent":"#"},
{"id":"jingling.rar","text":"jingling.rar","parent":"Junk"},
{"id":"Junk","text":"Junk","parent":"#"},
{"id":"pics.rar","text":"pics.rar","parent":"Junk"}
];


If you notice, the first and third objects in the array are same and so on. I've looked up for built in functions but I couldnt find any. IS there any simple built in. simple function to do this in jQuery or Javascript?

Answer

You can do something like this:

Array.prototype.getUnique = function(){
   var o = {}, a = [];
   for(var i = 0, l = this.length; i < l; ++i){
      if(o.hasOwnProperty(JSON.stringify(this[i]))) {
         continue;
      }
      a.push(this[i]);
      o[JSON.stringify(this[i])] = 1;
   }
   return a;
}

This will return you an array with unique values only. I don't think there is any built-in function for it.