sir-haver
sir-haver

Reputation: 3592

Sort an array of objects by property AND alphabetically

I understand how to sort an an array of objects by one property, but not how to re-sort the array again alphabetically (while keeping the sorting by property).

For example, I have an array:

    [
        {title: 'Hello', category: 'something'}, 
        {title: 'Good', category: 'something else'}, 
        {title: 'Monday', category: 'something'}, 
        {title: 'Evening', category: 'something'}, {title: 'Food', category: 'others'}
]

To sort the array by category:

array.sort(
          (a, b) => -b.category.localeCompare(a.category)
        )

However, how can I sort the items in each category alphabetically, in this array, while keeping the elements sorted by the category?

Upvotes: 0

Views: 33

Answers (1)

Konrad
Konrad

Reputation: 24651

If localeCompare returns 0, compare another field

const array = [{
    title: 'Hello',
    category: 'something'
  },
  {
    title: 'Good',
    category: 'something else'
  },
  {
    title: 'Monday',
    category: 'something'
  },
  {
    title: 'Evening',
    category: 'something'
  }, {
    title: 'Food',
    category: 'others'
  }
]

array.sort(
  (a, b) => {
    const category = -b.category.localeCompare(a.category)
    if (category) return category
    return a.title.localeCompare(b.title)
  }
)
console.log(array)

Upvotes: 2

Related Questions