使用 JavaScript 按屬性對物件進行分組


假設我們有一個包含有關某些水果和蔬菜的資料的物件陣列,如下所示 -

const arr = [
   {food: 'apple', type: 'fruit'},
   {food: 'potato', type: 'vegetable'},
   {food: 'banana', type: 'fruit'},
];

我們需要編寫一個接收此類陣列的 JavaScript 函式。

我們的功能應根據物件的“型別”屬性對陣列物件進行分組。

這意味著所有“水果”型別物件都分組在一起,“蔬菜”型別也單獨分組。

示例

此程式碼如下 -

const arr = [
   {food: 'apple', type: 'fruit'},
   {food: 'potato', type: 'vegetable'},
   {food: 'banana', type: 'fruit'},
];
const transformArray = (arr = []) => {
   const res = [];
   const map = {};
   let i, j, curr;
   for (i = 0, j = arr.length; i < j; i++) {
      curr = arr[i];
      if (!(curr.type in map)) {
         map[curr.type] = {type: curr.type, foods: []};
         res.push(map[curr.type]);
      };
      map[curr.type].foods.push(curr.food);
   };
   return res;
};
console.log(transformArray(arr));

輸出

控制檯中的輸出將如下所示 -

[
   { type: 'fruit', foods: [ 'apple', 'banana' ] },
   { type: 'vegetable', foods: [ 'potato' ] }
]

更新時間:2020 年 11 月 24 日

745 次觀看

開啟你的 職業生涯

完成課程並獲得認證

開始
廣告