Array Of Objects Having Duplicate Attribute Value
I have an array of object how can I get those objects having duplicate attribute value. var array = [{'id':1,'attr':5},{'id':2,'attr':3},{'id':3,'attr':5}];  Here it should return
Solution 1:
A single loop approach for unsorted data by using a hash table for temporary collecting the first object of a group or just to indicate duplicates of the group.
var array = [{ "id": 1, "attr": 5 }, { "id": 2, "attr": 3 }, { "id": 3, "attr": 5 }],
    hash = Object.create(null),
    result = array.reduce((r, o) => {
        if (o.attrin hash) {
            if (hash[o.attr]) {
                r.push(hash[o.attr]);
                hash[o.attr] = false;
            }
            r.push(o);
        } else {
             hash[o.attr] = o;
        }
        return r;
    }, []);
console.log(result);.as-console-wrapper { max-height: 100%!important; top: 0; }Solution 2:
You could use a generator function and a nested loop to check for duplicates:
 function* dupes(arr, key) {
    for(const [index, el] of arr.entries()) 
      for(const  el2 of arr.slice(index + 1)) 
        if(index !== index2 && el[key] === el2[key])
           yield [el, el2];
 }
So you can use it as:
for(const [dupe1, dupe2] ofdupes(yourArray, "attr"))
    console.log(`${dupe1} collides with ${dupe2}`);
Post a Comment for "Array Of Objects Having Duplicate Attribute Value"