Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
464 views
in Technique[技术] by (71.8m points)

javascript - Lodash从数组中删除重复项(Lodash remove duplicates from array)

This is my data:

(这是我的数据:)

[
    {
        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"    
    }
]

With Lodash, how could I remove objects with duplicate id keys?

(使用Lodash,如何删除具有重复ID键的对象?)

Something with filter, map and unique, but not quite sure.

(带有过滤器,地图和独特内容的东西,但不是很确定。)

My real data set is much larger and has more keys, but the concept should be the same.

(我的真实数据集更大,并且具有更多的键,但是概念应该相同。)

  ask by ChrisRich translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

_.unique no longer work for the current version as lodash 4.0.0 has this breaking change .

(_.unique用于当前版本,因为lodash 4.0.0具有此重大更改 。)

The functionally was splitted into _.uniq, _.sortedUniq, _.sortedUniqBy, & _.uniqBy

(在功能上分为_.uniq,_。sortedUniq,_。sortedUniqBy和_.uniqBy)

You could use _.uniqBy either by

(您可以通过_.uniqBy方式使用_.uniqBy)

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

or

(要么)

_.uniqBy(data, 'id');

Documentation: https://lodash.com/docs#uniqBy

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


For older versions of lodash( < 4.0.0 )

(对于lodash的旧版本(<4.0.0))

Assuming that the data should be unique by id and your data is stored in data variable, you can use unique() function like this:

(假设数据应按id唯一,并且您的数据存储在data变量中,则可以使用unique()函数,如下所示:)

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

Or simply

(或者简单地)

_.uniq(data, 'id');

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...