具有重复属性值的对象数组

时间:2018-05-16 11:31:01

标签: javascript jquery arrays object

我有一个对象数组,如何才能获得具有重复属性值的对象。

var array = [{"id":1,"attr":5},{"id":2,"attr":3},{"id":3,"attr":5}];

此处应返回array[0]array[2],因为这些元素具有重复的属性值(attr = 5)。 并且还返回唯一数组。 array = [{“id”:2,“attr”:3}];

2 个答案:

答案 0 :(得分:2)

通过使用哈希表临时收集组的第一个对象或仅表示组的重复项,对未排序数据采用单循环方法。



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




答案 1 :(得分:0)

您可以使用生成器函数和嵌套循环来检查重复项:

 function* dupes(arr, key) {
    for(const [index, el] of arr.entries()) 
      for(const  el2 of arr.slice(index + 1)) 
        if(index !== index2 && el[key] === el2[key])
           yield [el, el2];
 }

所以你可以用它作为:

 for(const [dupe1, dupe2] of dupes(yourArray, "attr"))
    console.log(`${dupe1} collides with ${dupe2}`);
相关问题