Lodash remove duplicates from array

浪尽此生 提交于 2019-11-27 10:34:48
ntalbs

_.unique no longer work for the current version as lodash 4.0.0 has this breaking change. The functionally was splitted into _.uniq, _.sortedUniq, _.sortedUniqBy, & _.uniqBy

You could use _.uniqBy either by

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

or

_.uniqBy(data, 'id');

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


For older versions of 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:

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

Or simply

_.uniq(data, 'id');

You could use lodash method _.uniqWith, it is available in the current version of lodash 4.17.2.

Example:

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 }]

More info: https://lodash.com/docs/#uniqWith

Or simply Use union, for simple array.

You can also use unionBy for 4.0.0 and later, as follows: let uniques = _.unionBy(data, 'id')

Simply use _.uniqBy(). It creates duplicate-free version of an array.

This is a new way and available from 4.0.0 version.

_.uniqBy(data, 'id');

or

_.uniqBy(data, obj => obj.id);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!