How to get the first element of Set in ES6 ( EcmaScript 2015)

JavascriptEcmascript 6

Javascript Problem Overview


In ES6, how do we quickly get the element?

in MDN Syntax for Set, I didn't find an answer for it.

Javascript Solutions


Solution 1 - Javascript

They don't seem to expose the List to be accesible from the instanced Object. This is from the EcmaScript Draft:

> 23.2.4 Properties of Set Instances > > Set instances are ordinary objects that inherit properties from the Set prototype. Set instances also have a [[SetData]] internal slot.

[[SetData]] is the list of Values the Set is holding.

A possible solution (an a somewhat expensive one) is to grab an iterator and then call next() for the first value:

var x = new Set();
x.add(1);
x.add({ a: 2 });
//get iterator:
var it = x.values();
//get first entry:
var first = it.next();
//get value out of the iterator entry:
var value = first.value;
console.log(value); //1

Worth mention too that:

Set.prototype.values === Set.prototype.keys

Solution 2 - Javascript

Another choice will be to use the for..of loop like so:

const mySet = new Set(["one", "two", 3]);
for (let item of mySet) {
    console.log(item);
    break;
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJavaScripterView Question on Stackoverflow
Solution 1 - JavascriptMinusFourView Answer on Stackoverflow
Solution 2 - Javascriptuser7153178View Answer on Stackoverflow