Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

In ES6, how do we quickly get the element?

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

like image 357
JavaScripter Avatar asked Sep 12 '15 13:09

JavaScripter


People also ask

How do you return the first element of an array?

Passing a parameter 'n' will return the first 'n' elements of the array. ES6 Version: var first = (array, n) => { if (array == null) return void 0; if (n == null) return array[0]; if (n < 0) return []; return array. slice(0, n); }; console.

How do you find the first value of a object?

Use object. keys(objectName) method to get access to all the keys of object. Now, we can use indexing like Object. keys(objectName)[0] to get the key of first element of object.

How do you find the first two elements of an array?

To get the first 2 elements of an array, call the slice method passing it a start index of 0 and an end index of 2 as parameters. The slice method will return a new array containing the first 2 elements of the original array.


1 Answers

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 
like image 176
MinusFour Avatar answered Sep 21 '22 02:09

MinusFour