使用下划线删除重复对象
2022-08-30 04:44:41
我有这种数组:
var foo = [ { "a" : "1" }, { "b" : "2" }, { "a" : "1" } ];
我想过滤它,使其具有:
var bar = [ { "a" : "1" }, { "b" : "2" }];
我尝试使用_.uniq,但我想因为它不等于它本身,它不起作用。有没有办法为下划线uniq提供覆盖的等于函数?{ "a" : "1" }
我有这种数组:
var foo = [ { "a" : "1" }, { "b" : "2" }, { "a" : "1" } ];
我想过滤它,使其具有:
var bar = [ { "a" : "1" }, { "b" : "2" }];
我尝试使用_.uniq,但我想因为它不等于它本身,它不起作用。有没有办法为下划线uniq提供覆盖的等于函数?{ "a" : "1" }
.uniq/.unique 接受回调
var list = [{a:1,b:5},{a:1,c:5},{a:2},{a:3},{a:4},{a:3},{a:2}];
var uniqueList = _.uniq(list, function(item, key, a) {
return item.a;
});
// uniqueList = [Object {a=1, b=5}, Object {a=2}, Object {a=3}, Object {a=4}]
笔记:
另一个例子:使用回调从列表中提取汽车品牌,颜色
如果您希望根据ID删除重复项,可以执行以下操作:
var res = [
{id: 1, content: 'heeey'},
{id: 2, content: 'woah'},
{id: 1, content:'foo'},
{id: 1, content: 'heeey'},
];
var uniques = _.map(_.groupBy(res,function(doc){
return doc.id;
}),function(grouped){
return grouped[0];
});
//uniques
//[{id: 1, content: 'heeey'},{id: 2, content: 'woah'}]