Search code examples
javascriptarraysecmascript-6ecmascript-5ecmascript-2016

Remove object, with a common property, from array


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',
}]

Solution

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