問題描述
使用 map/reduce 計算總數 (Using map/reduce to calculate totals)
我想創建一個對以下數據進行一些數組操作的函數(見下文)。想知道是否有使用 map/forEach 或 Reduce 的簡潔方法?
function calculateTotalSelections {
"selections":[
{
"item_selected": 1,
},
{
"item_selected": 3,
},
{
"item_selected": 4
},
{
"item_selected": 4
},
{
"item_selected": 1567486585
},
{
"item_selected": 1567486585
}
]
}
返回一些輸出,例如
項目 4 被選中兩次
項目 1 被選中一次
項目 1567486585 被選中一次
(約束:項目選擇可能未知)
參考解法
方法 1:
try creating this map via iterations
var output = {};
selections.forEach(function(val){
var value = val["item_selected"];
output[value] = output[value] || 0;
output[value]++;
});
Now output
has the frequency of each value
方法 2:
You can use reduce
to create an object with the items id as keys and their frequency as values.
selections.reduce(function(frequencies, item){
if (!item.item_selected) return frequencies;
frequencies[item.item_selected] = (frequencies[item.item_selected] || 0) + 1;
return frequencies;
}, {});
// ‑‑> { '1': 1, '3': 1, '4': 2, '1567486585': 2 }
(by user3788267、gurvinder372、VonD)