0

I have a array as bellow:

const list = [
  { id: 1, name: 'Product 1', color: 'white'},
  { id: 2, name: 'Product 2', color: 'black'},
  { id: 3, name: 'Product 3', color: 'red'},
  { id: 4, name: 'Product 4', color: 'white'},
  { id: 5, name: 'Product 5', color: 'black'},
]

I want to sort array based on predefined order by color: red -> white -> black and output:

const list = [
  { id: 3, name: 'Product 3', color: 'red'},
  { id: 1, name: 'Product 1', color: 'white'},
  { id: 4, name: 'Product 4', color: 'white'},
  { id: 5, name: 'Product 5', color: 'black'},
  { id: 2, name: 'Product 2', color: 'black'}
]
Alber Z
  • 27
  • 5
  • 1
    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) – mgm793 Jun 17 '20 at 07:22

1 Answers1

0
let colorPriority = ['red', 'white', 'black'];
list = list.sort((obj1, obj2) => colorPriority.indexOf(obj1.color) - colorPriority.indexOf(obj2.color));

this code should work for you.

Rajat Raj
  • 16
  • 1