How would I sort an array of objects using the values in the desiredOrder array? I want my array objects to be sorted by the type key in each object. I want all the fruit items to show first, then the drug items, then the wheat items. Etc. It would be preferred if the function was a reusable one.
// This is the order I want myList sorted in by the object property type
let desiredOrder = ['fruit', 'drugs', 'wheat', 'candy', 'vegetable', 'dairy']
// Here is my list of objects
let myList = [
{
type: "fruit",
subType: "apple"
},
{
type: "vegetable",
subType: "carrot"
},
{
type: "fruit",
subType: "orange"
},
{
type: "dairy",
subType: "milk"
},
{
type: "wheat",
subType: "bread"
},
{
type: "vegetable",
subType: "lettuce"
},
{
type: "fruit",
subType: "mango"
},
{
type: "drugs",
subType: 'cocaine'
},
{
type: "vegetable",
subType: "spinach"
},
{
type: "candy",
subType: "chocolate"
},
{
type: "vegetable",
subType: "celery"
},
{
type: "fruit",
subType: "pineapple"
},
]