Reputation: 5250
I'm trying to utilize lodash but cannot find a javascript function that will take this:
[
{item: {id: 1}, 'name': 'hi'},
{item: {id: 2}, 'name': 'hey'},
{item: {id: 1}, 'name': 'hello'}
];
and turn it into
[
{item: {id: 1}, 'name': 'hi'},
{item: {id: 2}, 'name': 'hey'}
];
So far I have in javascript this:
var mainThings = [
{item: {id: 1}, 'name': 'hi'},
{item: {id: 2}, 'name': 'hey'},
{item: {id: 1}, 'name': 'hello'}
];
uniqueMainsFunc = function() {
var ids = [],
mains = [];
_.forEach(mainThings, function(thing) {
if (ids.indexOf(thing.item.id) === -1) {
ids.push(thing.item.id);
mains.push(thing);
}
});
return uniqueMains;
};
In this scenario uniqueMains would only contain:
[
{item: {id: 1}, 'name': 'hi'},
{item: {id: 2}, 'name': 'hey'}
]
Is there a lodash function that can better handle this? After the .forEach I tried to use !_.some(uniqueNestedIds, thing.item.id) and it did not work.
Upvotes: 1
Views: 171
Reputation: 5881
You can use _.uniqBy
for this:
_.uniqBy(mainThings, function(item) {
return item.item.id;
});
See this Plnkr.
Upvotes: 2
Reputation: 8926
uniqBy method can solve your problem
var mainThings = [
{ item: { id: 1 }, 'name': 'hi' },
{ item: { id: 2 }, 'name': 'hey' },
{ item: { id: 1 }, 'name': 'hello' }
];
var uniq = _.uniqBy(mainThings, 'item.id')
console.log(uniq);
Result:
[ { item: { id: 1 }, name: 'hi' },
{ item: { id: 2 }, name: 'hey' } ]
Upvotes: 2