简体   繁体   English

如何计算和记录对象数组中的重复项

[英]How to count and record number duplicates in array of objects

I have an array and I need to count and record how many times each item is duplicated. 我有一个数组,我需要计算并记录每个项目重复多少次。 For example the following array: 例如以下数组:

let arr = [
  {item:"pen"},
  {item:"book"},
  {item:"pen"}
];

This should be returned: 这应该返回:

let arr = [
  {item:"pen", found: 2},
  {item:"book", found: 1},
  {item:"pen", found: 2}
]

The attribute "found" should indicate how many times an item appears in the array. 属性“找到”应指示项目在阵列中出现多少次。

you can use two loop one for iteration one for filter ie 您可以使用两个循环之一进行迭代,其中一个用于过滤器,即

arr.forEach(item => {
  item.found = arr.filter(filterObject => filterObject.item == item.item).length;
})

Try like this. 尝试这样。

I have looped the array 2 times and found the duplicate elements, then incremented the new found value. 我将数组循环了2次,找到了重复的元素,然后增加了新的found值。

 let arr = [ {item:"pen"}, {item:"book"}, {item:"pen"} ]; var newArr = []; arr.forEach(function(res){ res.found = 0; arr.forEach(function(data){ if(res.item === data.item){ res.found++; } }); newArr.push(res); }); console.log(newArr); 

There are many ways to skin this cat, some more efficient and some more maintainable. 有很多方法可以为这只猫蒙皮,其中一些方法更有效且更易于维护。 Here's a little bit of both (not the most efficient nor maintainable), which should be easy to follow: 两者都有一点(不是最有效或不可维护的),应该很容易理解:

 let arr = [ {item:"pen"}, {item:"book"}, {item:"pen"} ]; let found = {}; // Find repeated objects arr.forEach((obj,i)=>{ found[obj.item]=found[obj.item]||[]; found[obj.item].push(i) }) // Apply totals to original objects Object.values(found).forEach(indexes=> indexes.forEach(index=>arr[index].found = indexes.length) ); console.log(arr); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM