【问题标题】:Array of objects having duplicate attribute value [duplicate]具有重复属性值的对象数组[重复]
【发布时间】:2018-05-16 11:31:01
【问题描述】:

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

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

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

【问题讨论】:

  • @Cerbrus,不,op 想要数组中超过时间的那些。
  • @NinaScholz:查找重复项的过程没有改变。另外:没有尝试,这只是一个要求,期待工作代码作为回报。
  • Stack Overflow 不是免费的代码编写服务,请展示您的代码/努力以及实际问题所在。

标签: javascript jquery arrays object


【解决方案1】:

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

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

【讨论】:

  • 为什么是Object.create(null) 而不仅仅是{}
  • 它创建一个没有原型的空对象。
  • 你为什么要使用这样的嵌套函数来初始化hash?这不利于代码的可读性/可维护性。
  • 太棒了@NinaScholz
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-12-14
    • 1970-01-01
    • 2020-06-08
    • 2015-08-24
    • 1970-01-01
    • 2017-12-31
    相关资源
    最近更新 更多