Sometimes, we want to sort an array with TypeScript.
In this article, we’ll look at how to sort an array with TypeScript.
How to sort an array with TypeScript?
To sort an array with TypeScript, we call array’s sort method with a callback that compares the 2 values being sorted and return a number according to that.
For instance, we write
const stringArray: string[] = ["AB", "Z", "A", "AC"];
const sortedArray: string[] = stringArray.sort((n1, n2) => {
if (n1 > n2) {
return 1;
}
if (n1 < n2) {
return -1;
}
return 0;
});
to call stringArray.sort with a callback that compares the n1 and n2 values, where n1 and n2 are items in stringArray.
In the callback, we return 1 if n1 comes before n2.
We return -1 if we want to reverse the order of n1 and n2.
And we return 0 otherwise.
Conclusion
To sort an array with TypeScript, we call array’s sort method with a callback that compares the 2 values being sorted and return a number according to that.