【问题标题】:Check for duplicates in object-array and count them检查对象数组中的重复项并计算它们
【发布时间】:2015-12-17 22:48:07
【问题描述】:

我需要用这样的对象检查数组中的所有重复项:

var array = [{ 
    id: '123', 
    value: 'Banana', 
    type: 'article'
},
{ 
    id: '124', 
    value: 'Apple', 
    type: 'article'
},
{ 
    id: '125', 
    value: 'Banana', 
    type: 'images'
}]

现在我需要这样的结果:

{ 'Banana': 2 }

这意味着我只需要知道value 的重复项,并且我想知道有多少次相同的值

我想过类似的事情

var counts = {};
array.forEach(function(x) { counts[x.value] = (counts[x.value] || 0) + 1; });

但这给了我所有对象的计数值...我需要计算重复项(不是全部)。

【问题讨论】:

    标签: javascript jquery arrays javascript-objects


    【解决方案1】:

    使用.reduce().filter()Object.keys() 很容易。如果不能保证 ES5 内置,您可以使用 shims、实用程序库或只是简单的 for 循环。

    var array = [{
      id: '123',
      value: 'Banana',
      type: 'article'
    }, {
      id: '124',
      value: 'Apple',
      type: 'article'
    }, {
      id: '125',
      value: 'Banana',
      type: 'images'
    }]
    
    var counts = array.reduce(function(counts, item) {
      var value = item.value
      counts[value] = counts[value] + 1 || 1
      return counts
    }, {})
    
    var duplicateCounts = Object.keys(counts).filter(function(value) {
      return counts[value] > 1
    }).reduce(function(duplicateCounts, value) {
      duplicateCounts[value] = counts[value]
      return duplicateCounts
    }, {})
    
    console.log(duplicateCounts)

    【讨论】:

      【解决方案2】:

      您可以从每个元素中提取'value' 参数并保存在另一个数组中,然后使用.indexOf() 简单地检查'value' 的出现

          var arr = [{ 
          id: '123', 
          value: 'Banana', 
          type: 'article'
      },
      { 
          id: '124', 
          value: 'Apple', 
          type: 'article'
      },
      { 
          id: '125', 
          value: 'Banana', 
          type: 'images'
      },
      { 
          id: '126', 
          value: 'Apple', 
          type: 'images'
      },
      { 
          id: '126', 
          value: 'Kiwi', 
          type: 'images'
      }];
      
      var itemCollection = [];
      var duplicates = [];
      $.each(arr,function(i,o)
      {  
        if(itemCollection.indexOf(arr[i]["value"]) == -1)
           itemCollection.push(arr[i]["value"]);
        else
           duplicates.push("Duplicate found :" + arr[i]["value"]);
      });
      
      alert(duplicates);
      

      例如:https://jsfiddle.net/DinoMyte/6he7n9d1/1/

      【讨论】:

      • 但这并没有给我重复值的数量。如果有三个“香蕉”-> 3
      猜你喜欢
      • 2020-10-24
      • 2023-02-09
      • 2021-07-06
      • 2012-05-19
      • 1970-01-01
      • 2017-12-28
      • 2014-12-27
      • 2021-01-23
      • 1970-01-01
      相关资源
      最近更新 更多