A. Gladkiy
A. Gladkiy

Reputation: 3450

typescript sort is wrong

I have array:

let a = [{id: "-1", name: "a"}, { id: "0", name: "b" }, { id: "1", name: "c" }]

I do the following:

a = a.sort(x => <number>x.id);

But for some reasons I have item with id = "0" in the last position. What's the reason of it and how can I fix it?

Also I tried to change id = "0" -> id = "-2" in array but now if I sort again I see the following order: -1, -2, 1. What's wrong?

Maybe there is an error in casting one type to another? I mean string to number

Upvotes: 0

Views: 652

Answers (2)

Arsen
Arsen

Reputation: 99

Try this.

a.sort((a, b) => { if (a.id < b.id) return -1; else if (a.id > b.id) return 1; else return 0; });

Upvotes: 0

thedude
thedude

Reputation: 9812

Typescript is not a runtime language, it compiles to JS. Doing a TS cast will only instruct the TS compiler to treat x.id a a number it will not perform a runtime cast.

What you want is to do a JS cast to number, e.g. Number(x.id)

Also, to properly sort you'll need to compare two items:

a.sort((x, y) => Number(x.id) - Number(y.id))

Upvotes: 1

Related Questions