按陣列中的元素進行分組 JavaScript


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

const arr = [
   {"name": "toto", "uuid": 1111},
   {"name": "tata", "uuid": 2222},
   {"name": "titi", "uuid": 1111}
];

我們需要撰寫一個 JavaScript 函式,將物件拆分為一組陣列,這些陣列具有 uuid 屬性的類似值。

輸出

因此,輸出應如下所示 −

const output = [
   [
      {"name": "toto", "uuid": 1111},
      {"name": "titi", "uuid": 1111}
   ],
   [
      {"name": "tata", "uuid": 2222}
   ]
];

程式碼如下 −

const arr = [
   {"name": "toto", "uuid": 1111},
   {"name": "tata", "uuid": 2222},
   {"name": "titi", "uuid": 1111}
];
const groupByElement = arr => {
   const hash = Object.create(null),
   result = [];
   arr.forEach(el => {
      if (!hash[el.uuid]) {
         hash[el.uuid] = [];
         result.push(hash[el.uuid]);
      };
      hash[el.uuid].push(el);
   });
   return result;
};
console.log(groupByElement(arr));

輸出

控制檯中的輸出 −

[
   [ { name: 'toto', uuid: 1111 }, { name: 'titi', uuid: 1111 } ],
   [ { name: 'tata', uuid: 2222 } ]
]

更新於: 10-Oct-2020

361 次瀏覽

開啟你的 職業生涯

完成課程獲得認證

入門
廣告
© . All rights reserved.