-1

I am using above code and removing the items based on id
I am getting id is not defined while comparing i+1 item when i reaches to maximum array length. Appreciate your help....

var arr = [{"id":"0-block-0","left":206.5,"top":0},{"id":"0-block-1","left":446.5,"top":0},{"id":"0-block-2","left":474.5,"top":16},{"id":"0-block-2","left":686.5,"top":0}];

    Expecting outout = [{"id":"0-block-0","left":206.5,"top":0},{"id":"0-block-1","left":446.5,"top":0},{"id":"0-block-2","left":686.5,"top":0}]


    Array.prototype.unique = function(){                                    
        var passNum = this.length;
        var _self = this;
        // to repeat loops n*n times
        while(passNum>0){       
             for(var i = 0;i<this.length;i++) {                   
                 if(this[i].id==this[i+1].id){
                        var _indx = this.indexOf(this[i]);
                        this.splice(_indx,1);            
                }                            
            }                   
            passNum = passNum-1;
        }          
        return this;
    };

1 Answers1

0

You can do this with ES2015 Sets.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set

EDIT: If you can't use ES2015, there is a polyfill available.

Joe Attardi
  • 4,381
  • 3
  • 39
  • 41