簡體   English   中英

Javascript/ES2015,計算出現次數並存儲為數組中的對象

[英]Javascript/ES2015, count the number of occurrences and store as objects within an array

我正在從 JSON 提要中提取數據,並嘗試計算每個名稱 (name_class) 出現的次數。

我想以以下格式返回一個對象數組,其中 count 是指名稱出現的次數:

myArray = [{name:"John", count: 5}, {name: "Sarah", count: 2}, {name: "Oliver", count: 3}];

到目前為止,我有以下內容,但這不計算出現次數,它只是將另一個對象添加到數組中;

   let namestUi = {
    renderNames(names){
        var counter2 = [];
        let namesFound = names.map((name) => {
          let {name_class} = name;

            if(counter2.name == name_class){
              counter2.count++;
            } else { counter2.push({name: name_class, count: 1}); }
        });
        console.log(counter2);
        return namesFound;
      }
    };

這是構建對象數組,但不計算出現次數。

function count(names){
    // Count occurrences using a map (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map)
    let map = new Map();
    for (let name of names) {
        map.set(name, (map.get(name) || 0) + 1);
    }

    // Transform to array of { name, count }
    let result = [];
    for (let [name, count] of map) {
        result.push({name: name, count: count});
    }

    return result;
}

count(["a", "b", "c", "a", "b", "a"])
// [{"name":"a","count":3},{"name":"b","count":2},{"name":"c","count":1}]

您如何使用計數器變量存在一些問題。 您可以像訪問普通對象一樣訪問屬性,但您將其定義為數組。 此外,您的map回調函數沒有返回任何值。

您可以使用此代碼,它使用Map來按名稱鍵計數器,然后應用Array.from將該 Map 轉換為您請求的對象數組:

 let namestUi = { renderNames(names){ return Array.from( names.reduce( (counters, {name_class}) => counters.set(name_class, (counters.get(name_class) || 0) + 1), new Map() ), ([name, count]) => ({name, count}) ); } }; let result = namestUi.renderNames([ { name_class: "John" }, { name_class: "John" }, { name_class: "Frank" }, { name_class: "John" }, ]); console.log(result);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM