简体   繁体   English

有条件地从数组中删除重复项

[英]Conditionally remove duplicates from array

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? 我已经看过lodash的uniqBy,但是如何确保只有最短单位的重复项保留在数组中?

uniqBy保留找到的第一个项目,因此只需在过滤之前按unit.length排序:

_.uniqBy(_.sortBy(data, x => x.unit.length), 'topic')

Though this question is already answered, I tried it using native javascript APIs (in case someone wants to do it without using lodash)- 尽管此问题已得到解答,但我使用本机javascript API进行了尝试(以防有人想在不使用lodash的情况下进行操作)-

I used sort to sort the array according to shortest unit . 我使用sort根据shortest unit对数组进行排序。

And then grouped them by topic and chose first item as item with shortest unit (because it was sorted in first step). 然后将它们按topic分组,并选择第一项作为单位最短的项(因为它已在第一步中进行了排序)。

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 :) 我希望这有帮助 :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM