按数组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 } ]
]