Edward Tanguay
Edward Tanguay

Reputation: 193302

Why won't this TypeScript sort code correctly sort this array of objects based on property?

I converted some JavaScript code that sorts an array to TypeScript and can't get it to work. Does anyone know why this code won't sort the array?

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"
        }
    ]
}

The result is this:

[
  {
    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'
  }
]

Upvotes: 0

Views: 158

Answers (1)

GreyBeardedGeek
GreyBeardedGeek

Reputation: 30088

Because the return type for the comparison method should be a number, not a boolean. The value should be negative if a < b, positive if a > b, and 0 if a === b.

See How to sort object array based on key in typescript

Upvotes: 2

Related Questions