-2

Is there a way to remove an object from an array if a single property in that object is found in another object in that array?

const arr = [{
  car: 'bmw',
  notimportant: 'bla bla',
},{
  car: 'audi',
  notimportant: 'bli bli',
},{
  car: 'bmw',
  notimportant: 'ble ble',
},{
  car: 'golf',
  notimportant: 'blo blo',
}]

Also I would like to add a counter of how many duplicates there were

Expected result:

[{
  car: 'bmw',
  count: 1,
  notimportant: 'bla bla',
},{
  car: 'audi',
  count: 0,
  notimportant: 'bli bli',
},{
  car: 'golf',
  count: 0,
  notimportant: 'blo blo',
}]
Álvaro
  • 2,255
  • 1
  • 22
  • 48
  • have you tried anything? what does not work? – Nina Scholz Jan 12 '21 at 15:23
  • @NinaScholz I do not know where to start to get that result, I tried new Set in the past and works well when the objects are identical, but when is only one property I don't know how to compare it – Álvaro Jan 12 '21 at 15:25

2 Answers2

4

You can use Array#reduce with an object to store the values for each car.

const arr = [{
  car: 'bmw',
  notimportant: 'bla bla',
},{
  car: 'audi',
  notimportant: 'bli bli',
},{
  car: 'bmw',
  notimportant: 'ble ble',
},{
  car: 'golf',
  notimportant: 'blo blo',
}];
const res = Object.values(arr.reduce((acc,curr)=>{
  ++(acc[curr.car] = acc[curr.car] || {...curr, count: -1}).count;
  return acc;
}, {}));
console.log(res);
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
1

You can use lodash's uniqBy function to remove duplicates in an array by specifying a key:

_.uniqBy(arr, (e) => {
  return e.car;
});

Here's the doc if you're interested

i_arber
  • 178
  • 1
  • 5