具有重复属性值的对象数组
问题描述:
我有一个对象数组,如何获得那些属性值重复的对象.
I have an array of object how can I get those objects having duplicate attribute value.
var array = [{"id":1,"attr":5},{"id":2,"attr":3},{"id":3,"attr":5}];
此处应返回 array [0]
和 array [2]
,因为这些元素具有重复的属性值(attr = 5).并返回唯一数组.数组= [{"id":2,"attr":3}];
Here it should return array[0]
and array[2]
because these elements having duplicate attribute value (attr=5).
and also return unique array.
array = [{"id":2,"attr":3}];
答
一种单循环方法,通过使用哈希表临时收集组的第一个对象或仅指示组的副本来处理未排序的数据.
A single loop approach for unsorted data by using a hash table for temporary collecting the first object of a group or just to indicate duplicates of the group.
var array = [{ "id": 1, "attr": 5 }, { "id": 2, "attr": 3 }, { "id": 3, "attr": 5 }],
hash = Object.create(null),
result = array.reduce((r, o) => {
if (o.attr in hash) {
if (hash[o.attr]) {
r.push(hash[o.attr]);
hash[o.attr] = false;
}
r.push(o);
} else {
hash[o.attr] = o;
}
return r;
}, []);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }