-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;
    };
2
  • why do you get the second of the same id? Commented May 19, 2016 at 15:10
  • The normal way to ensure uniqueness is to put your id's in a set. Commented May 19, 2016 at 15:12

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.