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
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);
You could use lodash _.uniqBy(arr,'key') it would suit you, as you are already using lodash
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With