【问题标题】:Why won't this TypeScript sort code correctly sort this array of objects based on property?为什么这个 TypeScript 排序代码不能根据属性正确排序这个对象数组?
【发布时间】:2021-01-31 12:01:33
【问题描述】:

我将一些对数组进行排序的 JavaScript 代码转换为 TypeScript,但无法使其工作。有谁知道为什么这段代码不会对数组进行排序?

const quotes = getQuotes();

const ascendingText : any = (a: any, b: any) => a.text > b.text;

console.log(quotes.sort(ascendingText));

function getQuotes() : any {
    return [
        {
            "category": "tech",
            "text": "cccccccccccccccccccc",
            "rank": 2.4,
            "status": "dontPost"
        },
        {
            "category": "tech",
            "text": "ddddddddddddddd",
            "rank": 4.1,
            "status": "posted"
        },
        {
            "category": "tech",
            "text": "aaaaaaaaaaaaaa",
            "rank": 3.2,
            "status": "dontPost"
        },
        {
            "category": "tech",
            "text": "bbbbbbbbbbbbbbbbbbbbb",
            "rank": 3.1,
            "status": "dontPost"
        }
    ]
}

结果是这样的:

[
  {
    category: 'tech',
    text: 'cccccccccccccccccccc',
    rank: 2.4,
    status: 'dontPost'
  },
  {
    category: 'tech',
    text: 'ddddddddddddddd',
    rank: 4.1,
    status: 'posted'
  },
  {
    category: 'tech',
    text: 'aaaaaaaaaaaaaa',
    rank: 3.2,
    status: 'dontPost'
  },
  {
    category: 'tech',
    text: 'bbbbbbbbbbbbbbbbbbbbb',
    rank: 3.1,
    status: 'dontPost'
  }
]

【问题讨论】:

    标签: typescript


    【解决方案1】:

    因为比较方法的返回类型应该是数字,而不是布尔值。 如果 a b,则该值为正,如果 a === b,则该值为 0。

    How to sort object array based on key in typescript

    【讨论】:

    • 谢谢,是的,这行得通:a.text < b.text ? -1 : a.text > b.text ? 1 : 0
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-19
    • 1970-01-01
    • 2015-12-27
    • 1970-01-01
    • 1970-01-01
    • 2019-01-07
    • 1970-01-01
    相关资源
    最近更新 更多