检查对象数组中的重复项并对其进行计数

Check for duplicates in object-array and count them

本文关键字:数组 对象 检查      更新时间:2023-09-26

我需要检查具有以下对象的数组中的所有重复项:

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

但这给了我所有对象的计数值。。。我需要清点副本(不是全部)。

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

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)

您可以从每个元素中提取'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/