使用 map/reduce 計算總數 (Using map/reduce to calculate totals)


問題描述

使用 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 user3788267gurvinder372VonD)

參考文件

  1. Using map/reduce to calculate totals (CC BY‑SA 2.5/3.0/4.0)

#reduce #javascript #foreach #Dictionary #higher-order-functions






相關問題

Lapack 的行縮減 (Lapack's row reduction)

泡菜cython類 (pickle cython class)

將列表列表減少為字典,以子列表大小為鍵,出現次數為值 (Reduce list of list to dictionary with sublist size as keys and number of occurances as value)

使用 map/reduce 在列表中添加一對數字的差異 (Adding difference of pair of numbers in list using map/reduce)

Python 2.7:使用 reduce 驗證元素是否在列表中 (Python 2.7: Using reduce to verify that elements are in a list)

使用 map/reduce 計算總數 (Using map/reduce to calculate totals)

Swift reduce - 為什麼 value 是可選的? (Swift reduce - why is value optional?)

獲取具有對像一鍵值的數組的平均值 - Javascript (Get the avarage value of array with objects one key value - Javascript)

如何將數據數組轉換為在顫振/飛鏢中展開或折疊的小部件列表? (How to convert an array of data to a list of widgets with expand or fold in flutter/dart?)

樹的字符串路徑 (JavaScript) (String-path to Tree (JavaScript))

如何重命名對像數組中對象的所有鍵? (How does one rename all of an object's keys within an array of objects?)

使用reduce轉換一個js對象 (transform a js object using reduce)







留言討論