To sort items of a Set in JavaScript, 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 = new Set([5, 3, 8, 1, 2]);
const sortedArray = 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 = new Set(["banana", "apple", "cherry", "date"]);
const sortedArray = 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 JavaScript language with well detailed examples.