-1

I have an array of objects containing a particular structure. Then, I have an array (given by the user), which contains values in the order which the elements should be sorted. For simplicity, I'll give the following example:

const arrayOfObjects = [
{objectId: 1, color: 'Orange'},
{objectId: 2, color: 'Blue'},
{objectId: 3, color: 'White'},...
]

And the array given by the user for sorting:

['White', 'Orange', 'Blue']

Now my question is, how can I sort the first array, so that all objects with color white come first, then all the elements with orange color and then blue?

Note: The array will be given by the user, so cannot sort alphabetically.

VaibhavJoshi
  • 355
  • 2
  • 15
  • Does this answer your question? [Sort array of objects by string property value](https://stackoverflow.com/questions/1129216/sort-array-of-objects-by-string-property-value) – Omkar76 Oct 29 '20 at 11:37
  • No, that question is based on sorting the properties alphabetically. – VaibhavJoshi Oct 30 '20 at 07:03

1 Answers1

0

Okay, a little trial and error on my part resulted in the following code:

const sortedArray = arrayOfObjects.sort((a, b) => {
  return colors.findIndex(c => c === a.myColor) - colors.findIndex(c => c === b.myColor)
})
// colors being the array given by the user.
VaibhavJoshi
  • 355
  • 2
  • 15