-1

How to get second value in Set?

const set = new Set()

set.add('a')
set.add('b')
kennarddh
  • 2,186
  • 2
  • 6
  • 21

1 Answers1

3

You would have to loop over the set values until n values have been iterated over. While this works (JavaScript has a deterministic set order), it's unusual to write code that would use this and you may prefer to use an array which supports constant time array index access (perhaps in combination with a set, to handle duplicate prevention).

function getSetNth(set, n) {
    let i = 0;
    for (const v of set) {
        if (i++ === n) {
            return v;
        }
    }
    return null;
}

const set = new Set();

set.add('a');
set.add('b');

console.log(getSetNth(set, 1));

You could also turn a set into an array, for further processing.

const set = new Set();

set.add('a');
set.add('b');

const arr = [...set];

console.log(arr[1]);

When working with a library that returns a set, I would not assume that the library will return values in that set in a deterministic order (there may be subtle edge cases, and the implementation may change in future versions of the library). If the library intended you to access the values by index, they should have used a different data type.

Alexander O'Mara
  • 58,688
  • 18
  • 163
  • 171