使用Underscore for Javascript删除重复的对象 [英] Removing duplicate objects with Underscore for Javascript

查看:209
本文介绍了使用Underscore for Javascript删除重复的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这种数组:

var foo = [ { "a" : "1" }, { "b" : "2" }, { "a" : "1" } ];

我想将其过滤为:

var bar = [ { "a" : "1" }, { "b" : "2" }];

我尝试使用_.uniq,但我猜是因为 {a :1} 不等于它自己,它不起作用。有没有办法为下划线uniq提供覆盖等于函数?

I tried using _.uniq, but I guess because { "a" : "1" } is not equal to itself, it doesn't work. Is there any way to provide underscore uniq with an overriden equals function?

推荐答案

.uniq / 。 unique接受回调

.uniq/.unique accepts a callback

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

注意:


  1. 回调退货用于比较的值

  2. 具有唯一返回值的第一个比较对象用作唯一

  3. underscorejs.org 显示没有回调使用

  4. lodash.com 显示用法

  1. Callback return value used for comparison
  2. First comparison object with unique return value used as unique
  3. underscorejs.org demonstrates no callback usage
  4. lodash.com shows usage

另一个例子:
使用回调从列表中提取汽车品牌,颜色

这篇关于使用Underscore for Javascript删除重复的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆