To sort items of a Set in TypeScript, you can convert the Set to an Array and use the sort()
method.
In this example,
numberSet
with a set of numeric values.numberSet
to an Array using the Array.from()
method.sort()
method to sort the items in ascending order. The sort()
method without a compare function sorts the array elements as strings.(a, b) => a - b
to the sort()
method.const numberSet: Set<number> = new Set([5, 3, 8, 1, 2]);
const sortedArray: number[] = Array.from(numberSet).sort((a, b) => a - b);
console.log("Sorted array:", sortedArray);
Sorted array: [1, 2, 3, 5, 8]
In this example,
stringSet
with a set of string values.stringSet
to an Array using the Array.from()
method.sort()
method to sort the items in alphabetical order. The sort()
method without a compare function sorts the array elements as strings by default.const stringSet: Set<string> = new Set(["banana", "apple", "cherry", "date"]);
const sortedArray: string[] = Array.from(stringSet).sort();
console.log("Sorted array:", sortedArray);
Sorted array: ["apple", "banana", "cherry", "date"]
In this tutorial, we learned How to Sort Items of a Set in TypeScript language with well detailed examples.