检查对象数组中的重复项并计算它们

时间:2015-12-17 22:48:07

标签: javascript jquery arrays javascript-objects

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

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

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

2 个答案:

答案 0 :(得分:0)

您可以从每个元素中提取'value'参数并保存在另一个数组中,只需使用'value'

检查.indexOf()的出现位置
    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/

答案 1 :(得分:0)

.reduce().filter()Object.keys()很容易。如果无法保证ES5内置函数,您可以使用填充程序,实用程序库或简单的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)

相关问题