In this article, we will see how to sort the Set according to the value of the elements. One way of achieving the target is to use the in-built sort() function. But, the sort() function can’t be directly implemented on set, rather:
- We will generate an array container using the elements stored in the set.
- Then, we will execute the sort() function on the array.
- We shall clear the entire set and store the elements stored in the newly sorted array.
As the set returns elements in the same order as inserted, the whole set will now be sorted.
Below are the approaches through which we can sort the set:
- By iterating over the set
- Using Array.from() method
- Using Spread Operator and set() Constructor
Approach 1. By iterating over the set.
In this approach, we will iterate over the set manually and insert elements of the set into a new array that is about to get sorted according to our needs.
Syntax:
# myset is the set under consideration for this article
let myarr = [];
for (let element of myset) {
// Set elements pushed into the array
myarr.push(element);
}
# myArray consists of the elements of the set
myArray.sort()
Example:
JavaScript
let myset = new Set()
myset.add(3);
myset.add(2);
myset.add(9);
myset.add(6);
console.log(myset);
let myarr = [];
for (let element of myset) {
myarr.push(element);
}
console.log(myarr);
myarr.sort()
myset.clear()
for (let element of myarr) {
myset.add(element);
}
console.log(myset);
|
Output
Set(4) { 3, 2, 9, 6 }
[ 3, 2, 9, 6 ]
Set(4) { 2, 3, 6, 9 }
One way of generating the array is to use the in-built Array.from() method which will create an array out of the elements of the set. To know more about the method, follow this link.
Syntax:
# myset is the set under consideration for this article
myArray = Array.from(myset)
myArray.sort()
Example:
Javascript
let myset = new Set()
myset.add(3);
myset.add(2);
myset.add(9);
myset.add(6);
console.log(myset);
let myarr = [];
myArray = Array.from(myset)
myArray.sort()
console.log(myArray)
myset.clear()
myset = new Set(myArray);
console.log(myset)
|
Output
Set(4) { 3, 2, 9, 6 }
[ 2, 3, 6, 9 ]
Set(4) { 2, 3, 6, 9 }
In this method, we will convert the set into an array using spread syntax, and then by using the sort function we sort the set.
Example:
Javascript
let myset = new Set()
myset.add(3);
myset.add(2);
myset.add(9);
myset.add(6);
console.log(myset);
const sortedArray = [...myset].sort();
const newSet = new Set(sortedArray);
console.log(newSet);
|
Output
Set(4) { 3, 2, 9, 6 }
Set(4) { 2, 3, 6, 9 }
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
01 Aug, 2023
Like Article
Save Article