![](/img/trans.png)
[英]Compare an Array to an Array of Objects and Return a new Array of Objects with Grouped Dates
[英]Return a new array of objects with same values grouped by qauntity/length
所以我目前有一个这样的数组:
const allMeats = ['Bacon','Bacon','Bacon', 'Steak', 'Lettuce', 'Cabbage','Cabbage','Cabbage','Steak', 'Veal']
我想对数组进行变形,使其成为一个对象数组,其键/值确定重复项的值。
目前我有
const meatsGrouped = allMeats.reduce(
(acum, cur) => Object.assign(acum, { [cur]: (acum[cur] || 0) + 1 }),
[],
);
但是这段代码将数组转换为: [Bacon: 3, Steak: 2, Lettuce: 1, Cabbage: 3, Veal: 1]
,理想情况下我希望它看起来像这样: [{Bacon: 3}, {Steak: 2}, {Lettuce: 1}, {Cabbage: 3}, {Veal: 1}]
任何人都可以告诉我我做错了什么/失踪了吗?
您可以使用 reduce 和 map 方法来做到这一点。
const allMeats = [ 'Bacon', 'Bacon', 'Bacon', 'Steak', 'Lettuce', 'Cabbage', 'Cabbage', 'Cabbage', 'Steak', 'Veal', ]; const ret = Object.entries( allMeats.reduce((prev, c) => { const p = prev; const key = c; p[key] = p[key]?? 0; p[key] += 1; return p; }, {}) ).map(([x, y]) => ({ [x]: y })); console.log(ret);
您可以使用 reduce 方法执行以下操作,
let allMeats = ['Bacon','Bacon','Bacon', 'Steak', 'Lettuce', 'Cabbage','Cabbage','Cabbage','Steak', 'Veal'];
let res = allMeats.reduce((prev, curr) => {
const index = prev.findIndex(item => item.hasOwnProperty(curr));
if(index > -1) {
prev[index][curr]++;
}else {
prev.push({[curr]: 1});
}
return prev;
}, []);
console.log(res);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.