1

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 array[0] and array[2] because these elements having duplicate attribute value (attr=5). and also return unique array. array = [{"id":2,"attr":3}];

Jasbir Rana
  • 259
  • 3
  • 13
  • @Cerbrus, no, op wants the ones which are more than on time in the array. – Nina Scholz May 16 '18 at 11:35
  • 1
    @NinaScholz: The process of finding the duplicates doesn't change. Also: No attempt, this is just a requirement, expecting working code in return. – Cerbrus May 16 '18 at 11:37
  • 1
    Stack Overflow is not a free code writing service, please show your code/effort and what the actual problem is. – Cerbrus May 16 '18 at 11:38

2 Answers2

2

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.attr in 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; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

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] of dupes(yourArray, "attr"))
    console.log(`${dupe1} collides with ${dupe2}`);
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151