按属性和字母顺序对对象数组进行排序。

huangapple go评论70阅读模式
英文:

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: &#39;Hello&#39;,
    category: &#39;something&#39;
  },
  {
    title: &#39;Good&#39;,
    category: &#39;something else&#39;
  },
  {
    title: &#39;Monday&#39;,
    category: &#39;something&#39;
  },
  {
    title: &#39;Evening&#39;,
    category: &#39;something&#39;
  }, {
    title: &#39;Food&#39;,
    category: &#39;others&#39;
  }
]

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

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年1月8日 23:27:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/75048990.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定