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?

1
  • You can just sort them alphabetically Commented Feb 4, 2021 at 9:12

1 Answer 1

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)

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.