Ashley Howard
Ashley Howard

Reputation: 73

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!

Upvotes: 0

Views: 63

Answers (2)

adiga
adiga

Reputation: 35259

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" ]
}

Upvotes: 3

Shubham Verma
Shubham Verma

Reputation: 5054

It could be like this :

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

and so on.

Upvotes: -2

Related Questions