Imagine I have an array
products= [{
"Name":'xyz',
'ID': 1
},
{
"Name":'abc',
'ID': 5
},
{
"Name":'def',
'ID': 3
}
]
sortOrder=[3,1,5]
If I run the following code:
sortOrder.forEach((item) => {
products.sort((productA) => {
if (productA.ID=== item) { return 1; } else { return -1; }
});
});
The sorting is not as per the order specified in sortOrder. I want to sort the products array based on the sortOrder mentioned in the sortOrder array. So, the output of the above should be,
{ "Name":'def', 'ID': 3 },{ "Name":'xyz', 'ID': 1 },{ "Name":'abc', 'ID': 5 }
Any suggestions?