1

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.

2 Answers 2

2

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' } ]
Sign up to request clarification or add additional context in comments.

Comments

2

You can use _.uniqBy for this:

_.uniqBy(mainThings, function(item) {
    return item.item.id;
});

See this Plnkr.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.