0

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?

sir-haver
  • 3,096
  • 7
  • 41
  • 85
  • Does this answer your question? [Javascript sort function. Sort by First then by Second](https://stackoverflow.com/questions/9175268/javascript-sort-function-sort-by-first-then-by-second) – Wyck Jan 08 '23 at 15:38

1 Answers1

2

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)
Konrad
  • 21,590
  • 4
  • 28
  • 64
  • 2
    The pattern `if (X) return X; return Y;` is usually expressed in JavaScript as `return X || Y`. Also, an arrow function that just returns a single expression doesn't need a statement block (esp. a `return` statement). So: `(a, b) => -b.category.localeCompare(a.category) || a.title.localeCaompare(b.title)` – Wyck Jan 08 '23 at 15:46