0

I have an array that looks like this

[
    {
        topic: 'Topic 1',
        person: { ... },
        unit: 'ABC-DEF'
    },
    {
        topic: 'Topic 1',
        person: { ... },
        unit: 'ABC'
    },
    {
        topic: 'Topic 1',
        person: { ... },
        unit: 'ABC-123-DEF'
    },
    {
        topic: 'Topic 2',
        person: { ... },
        unit: 'ABC-123'
    }
]

"units" are organisational units in my company. If there are duplicates by topic I want to keep only the object with the shortest unit and remove all others. So the example from above becomes:

[
    {
        topic: 'Topic 1',
        person: { ... },
        unit: 'ABC'
    },
    {
        topic: 'Topic 2',
        person: { ... },
        unit: 'ABC-123'
    }
]

I already took a look at uniqBy from lodash but how can I make sure that only the duplicate with the shortest unit stays in the array?

2 Answers 2

1

uniqBy keeps the first item it finds, so just sort by unit.length before filtering:

_.uniqBy(_.sortBy(data, x => x.unit.length), 'topic')
Sign up to request clarification or add additional context in comments.

Comments

1

Though this question is already answered, I tried it using native javascript APIs (in case someone wants to do it without using lodash)-

I used sort to sort the array according to shortest unit.

And then grouped them by topic and chose first item as item with shortest unit (because it was sorted in first step).

Checkout this code -

var finalData = [];
var data = [
    {
        topic: 'Topic 1',
        person: {  },
        unit: 'ABC-DEF'
    },
    {
        topic: 'Topic 1',
        person: { },
        unit: 'ABC'
    },
    {
        topic: 'Topic 1',
        person: { },
        unit: 'ABC-123-DEF'
    },
    {
        topic: 'Topic 2',
        person: { },
        unit: 'ABC-123'
    }
];

data.sort((item1, item2) => {
    return item1.unit.length - item2.unit.length;
}).reduce(function(groups, item) {
    if (!groups[item.topic]) {
        finalData.push(item);
        groups[item.topic] = true;
    }
    return groups;
  }, {});
  
console.log(finalData);

I hope this helps :)

1 Comment

I fixed a couple of mistakes in your code, hope you don't mind.

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.