Lodash 从数组中删除重复项

Lodash remove duplicates from array

这是我的数据:

[
    {
        url: 'www.example.com/hello',
        id: "22"    
    },
    {
        url: 'www.example.com/hello',
        id: "22"    
    },
    {
        url: 'www.example.com/hello-how-are-you',
        id: "23"    
    },
    {
        url: 'www.example.com/i-like-cats',
        id: "24"    
    },
    {
        url: 'www.example.com/i-like-pie',
        id: "25"    
    }
]

使用 Lodash,如何删除具有重复 ID 键的对象? 有过滤器、地图和唯一性的东西,但不太确定。

我的真实数据集更大,键也更多,但概念应该是一样的。

_.unique 不再适用于当前版本的 Lodash,因为版本 4.0.0 具有 this breaking change_.unique 的功能分为 _.uniq_.sortedUniq_.sortedUniqBy_.uniqBy

您可以这样使用 _.uniqBy

_.uniqBy(data, function (e) {
  return e.id;
});

...或者像这样:

_.uniqBy(data, 'id');

文档:https://lodash.com/docs#uniqBy


对于旧版本的 Lodash (< 4.0.0):

假设数据应该由每个对象的 id 属性 唯一并且您的数据存储在 data 变量中,您可以像这样使用 _.unique() 函数:

_.unique(data, function (e) {
  return e.id;
});

或者像这样:

_.uniq(data, 'id');

您可以使用 lodash 方法 _.uniqWith,它在当前版本的 lodash 4.17.2 中可用。

示例:

var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 2 }];

_.uniqWith(objects, _.isEqual);
// => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]

更多信息: https://lodash.com/docs/#uniqWith

4.0.0及以后版本也可以使用unionBy,如下: 让 uniques = _.unionBy(data, 'id')

或者简单地使用 union,用于简单数组。

_.union([1,2,3,3], [3,5])

// [1,2,3,5]

只需使用_.uniqBy()。它创建数组的 duplicate-free 版本。

这是一种新方法,从 4.0.0 版本开始可用。

_.uniqBy(data, 'id');

_.uniqBy(data, obj => obj.id);

使用 lodash 版本 4+,您可以通过特定 属性 或整个对象删除重复对象,如下所示:

var users = [
  {id:1,name:'ted'},
  {id:1,name:'ted'},
  {id:1,name:'bob'},
  {id:3,name:'sara'}
];
var uniqueUsersByID = _.uniqBy(users,'id'); //removed if had duplicate id
var uniqueUsers = _.uniqWith(users, _.isEqual);//removed complete duplicates

来源:https://www.codegrepper.com/?search_term=Lodash+remove+duplicates+from+array

对于简单的数组,您可以使用并集方法,但您也可以使用:

_.uniq([2, 1, 2]);

在低于 4 的 LODASH 版本中,您会发现大部分功能的实现方式不同。与版本 4 相反 _.uniq 被修改。我个人有一个过渡了几个月的项目(从 V3 -> 到 V4)

如果你运行处于同样的情况并且你有很多功能需要更新。你可以分阶段进行,当你完成过渡后,你可以稍后来修复它。这是我用来避免平台停机的技巧:

/* LODASH Version 3 & 4 Compatibility Mode */
if ((_.VERSION).charAt(0) <= 3){ //Detect LODASH version 3 or 4.
    //V3 or lower
    _.uniq(data, true, 'id');
} else {
    //V4 or Higher
    _.uniqBy(data, 'id');
}

Also if you look at lodash documentation for most of this cases you can find migration of _.uniq from version lower than 4 can be performed with both functions:

_.uniqBy(data, 'id') or _.unionBy(data, 'id')

Both of them will bring same result. I personally was guessing which one to pick. In the end I picked this one: _.uniqBy(data, 'id').