2

I want to remove duplicates in an array of objects, depending on object attributes.

Simplified example: Assuming you have an array like:

[
 { 
   name: 'alice',
   something: 123
 },
 {
   name: 'alice',
   something: 321
 },
 {
  name: 'bob',
  something: 213
 }
]

I want to remove objects, wich have the same value for name, but I want to decide which object to remove with some custom calculation (e.g. keep the object with bigger value for something).

I was able to adapt the accepted answer in find duplicate values in a JavaScript array, but that does not work so well with more than 2 duplicates.

Community
  • 1
  • 1
zwif
  • 195
  • 3
  • 13

2 Answers2

1

You can try with reduce and object, set properties base on your condition.

Then convert it to array by Object.values.

var arr = [
 { 
   name: 'alice',
   something: 123
 },
 {
   name: 'alice',
   something: 321
 },
 {
  name: 'bob',
  something: 213
 }
];

var res = arr.reduce( (acc,b) => {
 if ((acc[b.name] && acc[b.name].something < b.something) || !acc[b.name]) {
  acc[b.name] = b;
 }
 return acc;
}, {});
var newArr = Object.values(res);
console.log(newArr);
taile
  • 2,738
  • 17
  • 29
1

You could use a hash table as reference to the same name objects.

var array = [{ name: 'alice',something: 123 }, { name: 'alice', something: 321 }, { name: 'bob', something: 213 }],
    result = array.reduce(function (hash) {
        return function (r, a) {
            if (!(a.name in hash)) {
                hash[a.name] = r.push(a) - 1;
                return r;
            }
            if (r[hash[a.name]].something < a.something) {
                r[hash[a.name]] = a;
            }
            return r;
        };
    }(Object.create(null)), []);
  
console.log(result)
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392