push only unique elements in an array

后端 未结 6 1377
-上瘾入骨i
-上瘾入骨i 2021-01-19 14:25

I have array object(x) that stores json (key,value) objects. I need to make sure that x only takes json object with unique key. Below, example \'id\' is the key, so i don\'t

6条回答
  •  时光说笑
    2021-01-19 14:48

    This is late but I did something like the following:

    let MyArray = [];
    MyArray._PushAndRejectDuplicate = function(el) {
        if (this.indexOf(el) == -1) this.push(el)
        else return;
    } 
    
    MyArray._PushAndRejectDuplicate(1); // [1]
    MyArray._PushAndRejectDuplicate(2); // [1,2]
    MyArray._PushAndRejectDuplicate(1); // [1,2]
    

提交回复
热议问题