Reputation: 3401
i have an array of objects like:
[{id: '123', name: 'John', someKey:'1234'}, {id: '123', name: 'John', someKey:'12345'}]
this is only a basic example, the data is much more complicated so _.isEqual
doesn't work.
what do I do with the comparator? I wanna compare the id
if they are equal.
_.uniqWith(myArray, function(something) {return something})
Upvotes: 5
Views: 21397
Reputation: 191976
Compare the ids in the _.uniqWith()
comparator function or use _.uniqBy()
:
var myArray = [{
id: '123',
name: 'John',
someKey: '1234'
}, {
id: '123',
name: 'John',
someKey: '12345'
}]
var result = _.uniqWith(myArray, function(arrVal, othVal) {
return arrVal.id === othVal.id;
});
console.log(result);
/** using uniqBy **/
var result = _.uniqBy(myArray, 'id');
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.16.6/lodash.min.js"></script>
Upvotes: 26