简体   繁体   English

从对象数组中删除重复项-下划线

[英]Remove duplicates from object array - Underscore

Trying to get _.uniq() working on the following structure: 尝试使_.uniq()在以下结构上工作:

[
    {'x' : 1, 'y': 2},
    {'x' : 1, 'y': 2},
    {'x' : 2, 'y': 3},
    {'x' : 2, 'y': 4},
    {'x' : 3, 'y': 4}
]

where the result should be: 结果应该是:

[
    {'x' : 1, 'y': 2},
    {'x' : 2, 'y': 3},
    {'x' : 2, 'y': 4},
    {'x' : 3, 'y': 4}
]

ie duplicate items removed. 即删除重复项。 I'd like to avoid stringify, because I then just have to parse each back out to a JSON object. 我想避免字符串化,因为然后只需要将每个解析回一个JSON对象即可。

Any help would be appreciated. 任何帮助,将不胜感激。

EDIT: tring Matt's solution below, I'm missing something I think - this doesn't work. 编辑:在下面寻找马特的解决方案,我错过了一些我认为的东西-这不起作用。 If I log the values for a and b, I see 如果我记录a和b的值,我会看到

_.uniq($scope.validNotes, function (a, b) {
    console.log(a, b);
    return a.x === b.x && a.y === b.y;
});


Object {x: 2, y: 3} 0 
Object {x: 1, y: 0} 1 
Object {x: 2, y: 3} 2 
Object {x: 3, y: 2} 3 
Object {x: 4, y: 2} 4
Object {x: 5, y: 1} 5

Which obviously means I'll never find any dupes 显然这意味着我永远都找不到骗子

Because two objects are not == or === , just because they have the same keys, you will need to use the [iterator] argument of the uniq() function ; 因为两个对象不是===== ,仅仅因为它们具有相同的键,所以您将需要使用uniq()函数[iterator]参数

_.uniq(myArray, function (item) {
    return item.x + item.y;
});

Note you'll need to return a unique string combination; 注意,您将需要返回唯一的字符串组合; consider the case of { x: 11, y: 1 } and { x: 1, y: 11 } ; 考虑{ x: 11, y: 1 }{ x: 1, y: 11 } my code will resolve both to 111 , and treat them as the same. 我的代码会将两者解析为111 ,并将它们视为相同。

Something like: 就像是:

_.uniq(myArray, function (item) {
    return 'x:' + item.x + 'y:' + item.y;
});

... would be more resilient, but it depends on the values of your data, of course. ……将更具弹性,但这当然取决于您的数据值。

If you have abstract data structure in your JSON, it will be better to compare array elements one bt one like strings, using stringify. 如果您的JSON中具有抽象数据结构,则最好使用stringify比较数组元素与字符串一样。 Because you have new object in every array element, every literal object notation ie {} creates new object in javascript language and it's doesn't metter has it the same properties or not. 因为每个数组元素中都有一个新对象,所以每个文字对象表示法(即{}都会以JavaScript语言创建新对象,并且具有相同的属性或不具有相同的属性。

But, if you have stucture like x,y use Matt answer 但是,如果您有x,y这样的结构,请使用马特答案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM