In this article we will learn how to get first element of set.
It is very common to get first element of set in JavaScript.
Problem
Now we have a problem, which is that we want to get the first element from the set.
Now let's define a set like this:
// set
const set = new Set([1, 2, 3, 4, 5]);
console.log(set);
And we only want the first element of the set, so the output becomes like this:
[1, 2, 3, 4, 5]
How to solve this problem?
There is more than one solution to this problem, such as:
- Using
keys().next()
methods Array.from()
method
Now we will explain these solutions in detail.
Get first element using keys()
method
We can use keys()
method to solve this problem.
but first we should know what keys()
method do?
The Object.keys() method returns an array of a given object's own enumerable string-keyed property names. (Source: MDN)
Example
// set
const set = new Set([1, 2, 3, 4]);
console.log(set.keys());
Output
[Set Iterator] { 1, 2, 3, 4 }
Now it is easy to get the first element using next()
method.
// set
const set = new Set([1, 2, 3, 4]);
console.log(set.keys().next().value);
Output
1
Since we call the next()
method only once on the iterable, it returns the first element in the sequence.
Get first element using Array.from
method
We can use Array.from
to solve this problem as well.
Array.from
will convert the set into an array, and then we can easily get the first element.
// Set
const set = new Set([1, 2, 3, 4]);
// Convert to array
const toArray = Array.from(set);
// Print the result:
console.log(toArray[0]);
Output
1
Thank you for reading
Thank you for reading my blog. 🚀