我建议(因为模式可能会有所不同)创建一个包含类别的数组以及这些类别包含哪些元素,从而创建一个带有标识类别的键的对象。
变量没有在对象外部“声明”,但您可以访问对象键的方式与拥有不同变量的方式相同:
// 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']);