The most efficient way to find a duplicate key in a list of objects

I have a list of objects that I am repeating. At some point, I make an ajax call to add more objects to the list (maybe many times).

Is there an effective way to exclude any objects from the list if one of the values ​​matches an existing value?

For instance:

Existing list

[ {"value": "1", "id": "123"}, {"value": "2", "id": "124"}, {"value": "3", "id": "125"} ] 

Exclude adding the first object, since it already has an identifier that is already in the list

 [ {"value": "1", "id": "123"}, {"value": "2", "id": "234"}, {"value": "3", "id": "235"} ] 
+4
source share
2 answers

Since your id is unique, why not use something like map .

  • You can create and save a separate var map = {};
  • Then each time a new object arrives, you do the following: map['123'] = true;

More likely:

 if (!map[new_id]) { map[new_id] = true; your_array.push({"value": "3", "id": "235"}); } else { // do what you want... maybe update the value } 

This way you will not click any objects with an existing id .

+5
source

The _array and _hash refer to the same objects, and therefore the memory overhead is limited to references in the array and hash, but not full copies of the objects.

Violin: http://jsfiddle.net/vbjWK/

 function UniqueArray(array, key) { this._array = []; this._hash = {}; this._key = key; this.concat(array); } UniqueArray.prototype.concat = function(array) { var i, len; for (i = 0, len = array.length; i < len; i++) { this.push(array[i]); } } UniqueArray.prototype.push = function(obj) { if (!this._hash[obj[this._key]]) { this._hash[obj[this._key]] = obj; this._array.push(obj); } } 

Test:

 // Testing testing var first = [ {"value": "1", "id": "123"}, {"value": "2", "id": "124"}, {"value": "3", "id": "125"} ]; var second = [ {"value": "1", "id": "123"}, {"value": "2", "id": "234"}, {"value": "3", "id": "235"} ] var ua = new UniqueArray(first, "id"); ua.concat(second); console.log(ua._array); 
+1
source

Source: https://habr.com/ru/post/1495444/


All Articles