Sometimes, we want to get the index of item in a JavaScript set.
In this article, we’ll look at how to get the index of item in a JavaScript set.
How to get the index of item in a JavaScript set?
To get the index of item in a JavaScript set, we can convert the set into an array and then use the array indexOf
method.
For instance, we write:
const s = new Set([1, 2, 3])
const index = [...s].indexOf(2)
console.log(index)
to create a set with the Set
constructor.
Then we spread the set s
into an array with the spread operator.
Next, we call indexOf
on the array with the value we want to find the index for.
Therefore, index
is 1.
Conclusion
To get the index of item in a JavaScript set, we can convert the set into an array and then use the array indexOf
method.