-1

I am trying to push objects into my array. The problem is some objects are duplicated.

My codes are as following:

var obj = {
             'obj1 {
                     'id':'1', 'title':'title 1'
                   },
             'obj2 {
                     'id':'2', 'title':'title 2'
                   },
             'obj3 {
                     'id':'3', 'title':'title 3'
                   }, //duplicated
             'obj3 {
                     'id':'3', 'title':'title 3'
                   },
             'obj4 {
                     'id':'4', 'title':'title 4'
                   }
             // and many more..
          }

var arr= [];

for (i in obj){
   arr.push(obj[i]) 
} 

I am not sure how to find out the duplicated obj and only push the unique objects into my arr.

Can someone help me out? Thanks a lot!

FlyingCat
  • 14,036
  • 36
  • 119
  • 198

2 Answers2

1

If your objects are stored in an array (it's hard to tell via your example) you could use the following function to get unique objects from that array based on one or more properties of the objects stored:

// get unique object members by property name(s)
function unique(arr, props) {
    var results = [],
        seen = [];
    for (var i=0; i < arr.length; i++){
        var key = "";
        for (var j=0; j < props.length; j++) {
            key += "" + arr[i][props[j]];
        }
        if (seen.indexOf(key) == -1) {
            seen.push(key);
            results.push(arr[i]);
        }
    }
    return results;
}

var obj = [
    { 'id': 1, 'title': 'title 1' },
    { 'id': 2, 'title': 'title 2' },
    { 'id': 3, 'title': 'title 3' },
    { 'id': 3, 'title': 'title 3' },
    { 'id': 4, 'title': 'title 4' }
];

var results = unique(obj, [ 'id', 'title' ]);
// results => [ obj[0], obj[1], obj[2], obj[4] ]
David Atchley
  • 1,204
  • 8
  • 10
0

You can dedupe this way if performance isn't an issue.

var deduped = {};
for (var i in obj) {
    deduped[JSON.stringify(obj[i])] = obj[i];
}
Fabricator
  • 12,722
  • 2
  • 27
  • 40