I suggest (since the pattern may vary) to create an array with categories and what elements those categories include, thus creating an object with keys identifying your categories.
The variables are not 'declared' outside the object but you can access the object keys the same way you'd have different variables:
// Simple old-style catalog as reference for your elements array.
var Categories = {
'fruits': ['orange', 'apple', 'all other fruits…'],
'vegetables': ['ginger', 'broccoli', 'all other vegetables…'],
'bread': ['pizza', 'panini', 'all other breads…'],
'sugars': ['soda', 'sugar1', '90_percent_of_products_are_sugar', 'all other sugars…']
};
// Your actual elements array.
var ElementsArray = [
'orange',
'broccoli',
'pizza',
'sugar1',
'apple',
'ginger',
'panini',
'soda'
];
// Your organized-by-category variable, declare as object so you can easily access as Array or Object (keys are the variable arrays).
var OrderedElementsArray = {};
for (element in ElementsArray)
{
for (category in Categories)
{
// Check if the key is not an array an initialize it for later use of push().
if (typeof OrderedElementsArray[category] != 'object')
{
OrderedElementsArray[category] = [];
}
// indexOf() returns -1 if no element matches an index, thus the expression `>= 0`.
if (Categories[category].indexOf(ElementsArray[element]) >= 0)
{
OrderedElementsArray[category].push(ElementsArray[element]);
}
}
}
// Here you can access your object variables with dot notation. All your categories will be accessible either way.
console.log(OrderedElementsArray.fruits);
console.log(OrderedElementsArray.vegetables);
console.log(OrderedElementsArray.bread);
console.log(OrderedElementsArray.sugars);
// Here you can access your object variables with key notation. All your categories will be accessible either way.
console.log(OrderedElementsArray['fruits']);
console.log(OrderedElementsArray['vegetables']);
console.log(OrderedElementsArray['bread']);
console.log(OrderedElementsArray['sugars']);