This is the opposite requirement to lodash unique based on attribute, here I want to make the array unique by ignoring one (or more) attribute.
So in the below, I don't care about the 'age' attribute (maybe there's multiple records, and I want to only keep where the details change).
const arr = [{
"id": 1,
"name": "Jen",
"age": 31,
"eyecolor": "blue",
"hair": "brown",
}, {
"id": 1,
"name": "Jen",
"age": 32,
"eyecolor": "blue",
"hair": "brown"
}, {
"id": 2,
"name": "Jules",
"age": 31,
"eyecolor": "blue",
"hair": "brown"
}, {
"id": 2 "name": "Brian",
"age": 40,
"eyecolor": "blue",
"hair": "brown"
}];
const unique = _.uniqBy(arr, 'id');
console.log(unique);
// const uniqueNot = _.uniqExcept(arr, 'age');
// keeps one of the Jen objects, but both of the Jules/Brian objects
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>
I want the above, as the comment says, to keep one of the Jen objects, but both of the Jules/Brian objects.
I think I can do this like so:
const arr = [{
"id": 1,
"name": "Jen",
"age": 31,
"eyecolor": "blue",
"hair": "brown",
}, {
"id": 1,
"name": "Jen",
"age": 32,
"eyecolor": "blue",
"hair": "brown"
}, {
"id": 2,
"name": "Jules",
"age": 31,
"eyecolor": "blue",
"hair": "brown"
}, {
"id": 2,
"name": "Brian",
"age": 40,
"eyecolor": "blue",
"hair": "brown"
}];
const omissionComparator = (withoutKeys) => (a, b) => _.isEqual(_.omit(a, withoutKeys), _.omit(b, withoutKeys))
const uniqueWithoutAge = _.uniqWith(_.orderBy(arr, ['id','age'], ['asc', 'desc']), omissionComparator('age'));
console.log(uniqueWithoutAge);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>
But is there a way of doing this without a custom comparator and/or having to sort the array first?
Maybe this? uniqBy + omit + JSON.stringify
const arr = [{
"id": 1,
"name": "Jen",
"age": 31,
"eyecolor": "blue",
"hair": "brown",
}, {
"id": 1,
"name": "Jen",
"age": 32,
"eyecolor": "blue",
"hair": "brown"
}, {
"id": 2,
"name": "Jules",
"age": 31,
"eyecolor": "blue",
"hair": "brown"
}, {
"id": 2,
"name": "Brian",
"age": 40,
"eyecolor": "blue",
"hair": "brown"
}];
const keysToIgore = ['age'];
const result = _.uniqBy(arr, o => JSON.stringify(_.omit(o, keysToIgore)));
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>