[英]How to count and record number duplicates in array of objects
我有一個數組,我需要計算並記錄每個項目重復多少次。 例如以下數組:
let arr = [
{item:"pen"},
{item:"book"},
{item:"pen"}
];
這應該返回:
let arr = [
{item:"pen", found: 2},
{item:"book", found: 1},
{item:"pen", found: 2}
]
屬性“找到”應指示項目在陣列中出現多少次。
您可以使用兩個循環之一進行迭代,其中一個用於過濾器,即
arr.forEach(item => {
item.found = arr.filter(filterObject => filterObject.item == item.item).length;
})
嘗試這樣。
我將數組循環了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);
有很多方法可以為這只貓蒙皮,其中一些方法更有效且更易於維護。 兩者都有一點(不是最有效或不可維護的),應該很容易理解:
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.