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, which 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.

2 Answers 2

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);

Sign up to request clarification or add additional context in comments.

Comments

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.