I have an array of objects that I'd like to sort using each object's property value compared against an ordered list of corresponding values.
Let's say I have this array of strings; food groups:
[ 'protein',
'dairy',
'fruit',
'vegetable' ]
And I also have an array of objects, food items, each belonging to one of the former food groups by the property group:
[
{ group: 'vegetable', name: 'broccoli' },
{ group: 'protein', name: 'beef' },
{ group: 'fruit', name: 'apple' },
{ group: 'vegetable', name: 'peas' },
{ group: 'dairy', name: 'cheese' },
{ group: 'protein', name: 'tofu' },
{ group: 'vegetable', name: 'bell pepper' },
{ group: 'dairy', name: 'milk' },
{ group: 'fruit', name: 'grapes' },
{ group: 'protein', name: 'chicken' },
]
Given the order of the food groups in the first array, how can I sort the food items using their object group properties, to result in this:
[
{ group: 'protein', name: 'beef' },
{ group: 'protein', name: 'tofu' },
{ group: 'protein', name: 'chicken' },
{ group: 'dairy', name: 'cheese' },
{ group: 'dairy', name: 'milk' },
{ group: 'fruit', name: 'apple' },
{ group: 'fruit', name: 'grapes' },
{ group: 'vegetable', name: 'broccoli' },
{ group: 'vegetable', name: 'peas' },
{ group: 'vegetable', name: 'bell pepper' },
]
While I'm doing this in Javascript, I'm sure this would be more or less the same across a few languages.
Any help is greatly appreciated!