简体   繁体   中英

How to extract values from a multidimensional array to form another array?

So I have an array with 4 values: 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],
...
]

How do I make more arrays to categorise them like this:

var beverages = ["coke", "pepsi", "water"]; // more drinks from above array...
var bread = ["baguette", "wholemeal"]; // more types of bread from above array...

Any help would be appreciated, thanks!

You could use reduce to group the items like this. Create an accumulator object with each type of food as key. Destructure each inner array to get the first and second item.

 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) 

This is how the grouped object will look. You can use destrucutring to get more categories of food

{
  "beverages": [ "coke", "water", "pepsi" ],
  "bread": [ "baguette", "wholemeal" ]
}

It could be like this :

var beverages = MyArray.map(data =>  data[0])
var bread = MyArray.map(data =>  data[1]);

and so on.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM