减少/分组JavaScript中的数组 [英] Reducing/Grouping an array in Javascript
本文介绍了减少/分组JavaScript中的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
基于此示例,我想以其他方式对对象进行分组.结果应该如下:
Based on this example, I want to group by object in a slightly other way. The outcome should be as follows:
[{
key: "audi"
items: [
{
"make": "audi",
"model": "r8",
"year": "2012"
},
{
"make": "audi",
"model": "rs5",
"year": "2013"
}
]
},
...
]
我该如何实现?我编写的以下代码无法实现我想要的功能:
How can I achieve that? The following code I wrote doesn't do what I want:
reduce(function (r, a) {
r[a.art] = {key: r[a.art], items: []} || [];
r[a.art].items.push(a);
return r;
}, Object.create(null));
推荐答案
您可以使用哈希表按make
进行分组,并使用所需结果的数组.
You could use a hash table for grouping by make
and an array for the wanted result.
对于hash
中的每个组,都有一个新对象,例如
For every group in hash
, a new object, like
{
key: a.make,
items: []
}
已创建并推送到结果集.
is created and pushed to the result set.
哈希表用一个真正空的对象初始化.没有原型,可以防止碰撞.
The hash table is initialized with a really empty object. There are no prototypes, to prevent collision.
var cars = [{ make: 'audi', model: 'r8', year: '2012' }, { make: 'audi', model: 'rs5', year: '2013' }, { make: 'ford', model: 'mustang', year: '2012' }, { make: 'ford', model: 'fusion', year: '2015' }, { make: 'kia', model: 'optima', year: '2012' }],
hash = Object.create(null),
result = [];
cars.forEach(function (a) {
if (!hash[a.make]) {
hash[a.make] = { key: a.make, items: [] };
result.push(hash[a.make]);
}
hash[a.make].items.push(a);
});
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
这篇关于减少/分组JavaScript中的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文