英文:
Sort an array of objects by property AND alphabetically
问题
我知道如何按一个属性对对象数组进行排序,但不知道如何再次按字母顺序重新排序数组(同时保持按属性排序)。
例如,我有一个数组:
[
    {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) => -b.category.localeCompare(a.category))
然而,如何在这个数组中按每个类别按字母顺序对项目进行排序,同时保持按类别排序的元素?
英文:
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?
答案1
得分: 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)
Note: I've only provided the translation of the code portion as requested.
英文:
If localeCompare returns 0, compare another field
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
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)
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论