I have a JavaScript array that is something like this:
var items = [
{ id:1, group:'Produce', name:'Apple', weight: 0.5 },
{ id:2, group:'Produce', name:'Banana', weight: 0.2 },
{ id:3, group:'Meat', name:'Beef', weight: 1.0 },
{ id:4, group:'Meat', name:'Chicken', weight: 0.75 },
{ id:5, group:'Dairy', name:'Milk', weight:1.0 }
];
I want to look through this array and dynamically put them in arrays by their group. I tried the following, however, it didn't work:
var groups = [];
for (var i = 0; i<items.length; i++) {
var groupName = items[i].group;
if (groups.includes(groupName) === false) {
groups[groupName] = new Array();
}
groups[groupName].push(items[i]);
}
Basically, I'm trying to create a Hashtable in JavaScript. The key is the group name and the value is an Array of items in that group. However, I've been unsuccessful. What am I missing here?
Thank you so much for your help!