Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove duplicate objects from an array excluding specific keys in JavaScript

I have this array:

[{name: 'Brad', age: 30, isOlder: true, youngerBrother: 'Oleg'}, {name: 'Brad', age: 30, isOlder: false, youngerBrother: 'Michael'}]

I want to check if the items on the list are duplicated by specific keys.

for example - if name, age are the same on the list, the rows are duplicated, without paying attention to isOlder or youngerBrother.

I tried to use lodash _uniq but there is no option for excluding keys/paying attention to specific keys

like image 646
Roni Litman Avatar asked Aug 13 '26 12:08

Roni Litman


2 Answers

You can use .filter() and .some():

var list = [
  {name: 'Brad', age: 30, isOlder: true, youngerBrother: 'Oleg'},
  {name: 'Brad', age: 30, isOlder: false, youngerBrother: 'Michael'}
];

list = list.filter(function(outer, oPos) {
  return !list.some(function(inner, iPos) {
    return iPos > oPos && inner.name == outer.name && inner.age == outer.age;
  });
});

console.log(list);

However, it would be more efficient to start the inner loop at oPos + 1 directly:

var list = [
  {name: 'Brad', age: 30, isOlder: true, youngerBrother: 'Oleg'},
  {name: 'Brad', age: 30, isOlder: false, youngerBrother: 'Michael'}
];

list = list.filter(function(outer, oPos) {
  for(var iPos = oPos + 1; iPos < list.length; iPos++) {
    if(list[iPos].name == outer.name && list[iPos].age == outer.age) {
      return false;
    }
  }
  return true;
});

console.log(list);

Alternatively, we can build a list of the encountered composite keys as we are iterating in .filter(). Most browsers should implement if(keyList[key]) as a lookup in a hash table, making it quite fast.

var list = [
  {name: 'Brad', age: 30, isOlder: true, youngerBrother: 'Oleg'},
  {name: 'Brad', age: 30, isOlder: false, youngerBrother: 'Michael'}
];

var keyList = {};

list = list.filter(function(obj) {
  var key = obj.name + '|' + obj.age;
  
  if(keyList[key]) {
    return false;
  }
  keyList[key] = true;
  return true;
});

console.log(list);
like image 139
Arnauld Avatar answered Aug 16 '26 02:08

Arnauld


You could use lodash _.uniqBy(arr,'key') it would suit you, as you are already using lodash

like image 44
Shintu Joseph Avatar answered Aug 16 '26 00:08

Shintu Joseph



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!