所以我有一个包含4个值的数组:item,category,checked,number:
var MyArray = [
["coke", "beverages", "checked", 000],
["baguette", "bread", "checked", 001],
["water", "beverages", "checked", 000],
["pepsi", "beverages", "checked", 000],
["wholemeal", "bread", "checked", 001],
...
]
我如何制作更多数组来对它们进行如下分类:
var beverages = ["coke", "pepsi", "water"]; // more drinks from above array...
var bread = ["baguette", "wholemeal"]; // more types of bread from above array...
任何帮助将不胜感激,谢谢!
答案 0 :(得分:3)
您可以使用reduce
对项目进行分组。使用每种食物作为关键字创建一个累加器对象。 Destructure
每个内部数组都将获得第一项和第二项。
var MyArray = [
["coke", "beverages", "checked", 000],
["baguette", "bread", "checked", 001],
["water", "beverages", "checked", 000],
["pepsi", "beverages", "checked", 000],
["wholemeal", "bread", "checked", 001],
]
const grouped = MyArray.reduce((r, [item, type]) => {
r[type] = r[type] || [];
r[type].push(item)
return r;
}, {})
const { bread, beverages } = grouped
console.log(bread, beverages)
这是grouped
对象的外观。您可以使用去屑获取更多种类的食物
{
"beverages": [ "coke", "water", "pepsi" ],
"bread": [ "baguette", "wholemeal" ]
}
答案 1 :(得分:-1)
可能是这样的:
var beverages = MyArray.map(data => data[0])
var bread = MyArray.map(data => data[1]);
以此类推。