具有重复属性值的对象数组 [英] Array of objects having duplicate attribute value
本文介绍了具有重复属性值的对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个对象数组,如何获得那些属性值重复的对象.
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; }
这篇关于具有重复属性值的对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文