Javascript - 在对象数组中查找(不删除)具有重复属性的元素

时间:2016-07-31 19:31:13

标签: javascript mapreduce

我想获取一个对象数组,检查多个属性是否同时重复。最后,意图提醒重复元素。即阵列:

[
  {
    "language" : "english",
    "type" : "a",
    "value" : "value1"
  },
  {
    "language" : "english",
    "type" : "a",
    "value" : "value2"
  },
  {
    "language" : "english",
    "type" : "b",
    "value" : "value3"
  },    
  {
    "language" : "spanish",
    "type" : "a",
    "value" : "valor1"
  }
];

警告应为:"语言英语的元素过多,输入 a "

我寻求它,但答案是脏地图/减少实现,使VisualStudio2015生气或找到完整的副本(不仅基于特定的属性)

1 个答案:

答案 0 :(得分:0)

性能方面,我认为最好的选择是在更新遇到密钥的计数器时迭代列表的每个元素。

您希望在counter == 2时提醒您。您不应该测试counter > 1,因为当您使用相同语言和相同类型的两对以上时,它会多次重复相同的警报。

var list = [{
    "language" : "english",
    "type" : "a",
    "value" : "value1"
  },{
    "language" : "english",
    "type" : "a",
    "value" : "value2"
  },{
    "language" : "english",
    "type" : "a",
    "value" : "value3"
  },{
    "language" : "english",
    "type" : "b",
    "value" : "value3"
  },{
    "language" : "spanish",
    "type" : "a",
    "value" : "valor1"
  },{
    "language" : "spanish",
    "type" : "a",
    "value" : "valor2"
}];

var counter = {};

list.forEach(function(o) {
  var key = o.language + '|' + o.type;
  if((counter[key] = (counter[key] || 0) + 1) == 2) {
    console.log('Too many elements with language '+o.language+' and type '+o.type);
  }
});