0

I have an array of items that I want to sort based on the category property:

const arr = [{
  id: 1,
  category: 'bar'
}, {
  id: 4,
  category: 'baz'
},
{
  id: 5,
  category: 'foo'
}]

What I want is to sort it based on the following order:

- foo
- bar
- baz

How can I do it with an array comparator?

arr.sort(function(a, b) {
  return ?
})

Do I need to give each category an order number and do a.order - b.order? Or there is another clever way to do it?

undefined
  • 6,366
  • 12
  • 46
  • 90
  • You can just sort them [alphabetically](https://stackoverflow.com/questions/8900732/sort-objects-in-an-array-alphabetically-on-one-property-of-the-array) – Reyno Feb 04 '21 at 09:12

1 Answers1

1

You can put your order into an array and use indexOf within sort.

const arr = [{
  id: 1,
  category: 'bar'
}, {
  id: 4,
  category: 'baz'
},
{
  id: 5,
  category: 'foo'
}]

const order = ["foo","bar","baz"]

arr.sort( (a,b) => order.indexOf(a.category) - order.indexOf(b.category) )
console.log(arr)
Jamiec
  • 133,658
  • 13
  • 134
  • 193