Borislav Hadzhiev
Tue Oct 05 2021·2 min read
Photo by Julian Hochgesang
To get the first element of a Set, use destructuring assignment, e.g.
const [first] = set
. The destructuring assignment sets the variable to the
first element of the Set.
const set = new Set([1, 2, 3]); const [first] = set; console.log(first); // 👉️ 1
In the code snippet, we used destructuring assignment to get the first element of the set and assign it to a variable.
1
to the variable named first
.We can get the second element of the set in a similar way:
const set = new Set([1, 2, 3]); const [, second] = set; console.log(second); // 👉️ 2
In the code snippet, we skip the first element by adding a ,
to the denote the
place of the first element in the destructuring assignment.
We can also get the first element of a set using the spread syntax.
To get the first element of a set, use the spread syntax to convert the set
into an array and access the element at index 0
, e.g.
const first = [...set][0]
.
const set = new Set([1, 2, 3]); const first = [...set][0]; console.log(first); // 👉️ 1
We can iterate over a set, so we can also convert the set into an array and use
the index to access the element at position 0
.
A more long winded way to get the first element of a set is to use the methods on the set instance.
const set = new Set([1, 2, 3]); const values = set.values(); // 👉️ iterator const obj = values.next() // 👉️ {value: 1, done: false} const first = obj.value; console.log(first); // 👉️ 1
In the code snippet we call the values
method on the set to get an iterator.
We call the next
method on the iterator to get an object containing the value
of the first iteration.
Finally, we access the value
property on the object to get the value of the
first element in the set.