gpt4 book ai didi

javascript - 按类别排列的产品数组

转载 作者:行者123 更新时间:2023-12-01 15:37:03 25 4
gpt4 key购买 nike

我正在尝试按类别排列这一系列产品。现在,我得到了每个类别的计数,但我不知道如何使这个二维数组输出。

let products = [
{name: 'Tequila', category: 'drink'},
{name: 'Beer', category: 'drink'},
{name: 'Burger', category: 'food'},
{name: 'Shawarma', category: 'food'},
{name: 'Wine', category: 'drink'},
{name: 'Gelatto', category: 'dessert'}
];

/*expected ouput

let arranged = [[
{name: 'Tequila', category: 'drink'},
{name: 'Beer', category: 'drink'},
{name: 'Wine', category: 'drink'}
], [
{name: 'Burger', category: 'food'},
{name: 'Shawarma', category: 'food'}
], [
{name: 'Gelatto', category: 'dessert'}
]];

*/
这是我现在的代码:

let products = [
{name: 'Tequila', category: 'drink'},
{name: 'Beer', category: 'drink'},
{name: 'Burger', category: 'food'},
{name: 'Shawarma', category: 'food'},
{name: 'Wine', category: 'drink'},
{name: 'Gelatto', category: 'dessert'}
];

let arranged = {};

products.map(x => arranged[x.category] = 1 + (arranged[x.category] || 0));

console.log(arranged);

最佳答案

您可以通过使用对象对数组进行归约来对元素进行分组,以存储属于每个类别的元素。要获得分组的类别,我们可以使用 Object.values .

let products = [{name: 'Tequila', category: 'drink'}, 
{name: 'Beer', category: 'drink'},
{name: 'Burger', category: 'food'},
{name: 'Shawarma', category: 'food'},
{name: 'Wine', category: 'drink'},
{name: 'Gelatto', category: 'dessert'}];
const res = Object.values(
products.reduce((acc,curr)=>(
(acc[curr.category] = acc[curr.category] || []).push(curr), acc
), {})
);
console.log(res);

关于javascript - 按类别排列的产品数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63383560/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com