0

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!

6
  • var beverages = MyArray[0] ? Commented May 21, 2019 at 17:46
  • You cannot create dynamic variable names, only dynamic keys of an object. You could e.g. create the following structure: var object = { beverages: [...], bread: [...] }; Commented May 21, 2019 at 17:48
  • What comes after "coke",... It's not obvious from the data Commented May 21, 2019 at 17:49
  • Are the items you want to group by always in the second position? Please show more data, perhaps with different beverages... Commented May 21, 2019 at 17:49
  • sorry more beverages come after coke Commented May 21, 2019 at 17:50

2 Answers 2

3

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" ]
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for this! Which part of this code takes the bread and beverages' items? The const? Just asking in case in the future I want to add more categories.
@AshleyHoward I have updated the answer. From reduce, you get an object with each unique category as it's key. If you have more types, you can add the key names to the destructuring const { bread, beverages, dessert } = grouped
-2

It could be like this :

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

and so on.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.