按数组 JavaScript 中的元素分组

javascriptweb developmentfront end technologyobject oriented programming更新于 2026/1/18 8:12:17

假设,我们有一个像这样的对象数组 −

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 } ]
]

相关文章


有用资源