對陣列進行分組和統計專案,根據 JavaScript 中的分組建立一個新陣列


假設我們有一個這樣的物件陣列 -

const arr = [
   { region: "Africa", fruit: "Orange", user: "Gary" },
   { region: "Africa", fruit: "Apple", user: "Steve" },
   { region: "Europe", fruit: "Orange", user: "John" },
   { region: "Europe", fruit: "Apple", user: "bob" },
   { region: "Asia", fruit: "Orange", user: "Ian" },
   { region: "Asia", fruit: "Apple", user: "Angelo" },
   { region: "Africa", fruit: "Orange", user: "Gary" }
];

我們需要寫一個 JavaScript 函式來輸入一個這樣的陣列。該函式應當準備一個新的物件陣列,根據物件的“area”屬性對資料進行分組。

該函式還應統計特定區域的唯一使用者數量。

因此,對於上述陣列,輸出應如下所示 -

const output = [
   {
      "region": "Africa",
      "count": 2
   },
   {
      "region": "Europe",
      "count": 2
   },
   {
      "region": "Asia",
      "count": 2
   }
];

示例

程式碼如下 -

const arr = [
   { region: "Africa", fruit: "Orange", user: "Gary" },
   { region: "Africa", fruit: "Apple", user: "Steve" },
   { region: "Europe", fruit: "Orange", user: "John" },
   { region: "Europe", fruit: "Apple", user: "bob" },
   { region: "Asia", fruit: "Orange", user: "Ian" },
   { region: "Asia", fruit: "Apple", user: "Angelo" },
   { region: "Africa", fruit: "Orange", user: "Gary" }
];
const groupByArea = (arr = []) => {
   const res = [];
   arr.forEach(el => {
      let key = [el.region, el.user].join('|');
      if (!this[el.region]) {
         this[el.region] = { region: el.region, count: 0 };
         res.push(this[el.region]);
      };
      if (!this[key]) {
         this[key] = true;
         this[el.region].count++;
      };
   }, Object.create(null));
   return res;
}
console.log(groupByArea(arr));

輸出

控制檯中的輸出將為 -

[
   { region: 'Africa', count: 2 },
   { region: 'Europe', count: 2 },
   { region: 'Asia', count: 2 }
]

更新於: 2020 年 11 月 24 日

196 次瀏覽

開始你的 職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.