12

I am playing with Set in Node.JS v0.11.3 and the --harmony flag. The API works fine, I can add, remove, clear, etc. I have however not been able to initialise a set with an array. I have tried (as prompted by the MDN page)

var mySet = new Set([1, 1, 2]);

How can I convert an array to a set? Is MDN outdated? Has Node.JS simply not implemented the feature?

asked Jul 7, 2013 at 19:27
3
  • looking at the code won't tell ? Commented Jul 7, 2013 at 19:43
  • For newcomers, node v12 does support this. Commented Aug 26, 2015 at 20:53
  • Cant seem to get this working in Node V4 Commented Sep 18, 2015 at 2:03

4 Answers 4

5

The v8 implementation of the Set constructor does not yet support the iterator and comparator arguments mentioned in §15.16.1.1 of the current draft of the Harmony specification, and node uses v8 as its JavaScript interpreter.

As a band-aid, you can use the simplesets package.

answered Jul 7, 2013 at 19:54
Sign up to request clarification or add additional context in comments.

Comments

3

Works fine in v8 now using an array supplied to a constructor. I'm using node v6.2.0 (v8 version 5.0.71.47).

> let mySet = new Set([1,2,3]);
undefined
> mySet;
Set { 1, 2, 3 }
> for ( let key of mySet ) { console.log(key) }
1
2
3
undefined
> mySet.size
3

Comments

1

From what I have read it is my understanding that the implementation of this is new and experimental. Some things might not work properly. Also I have noted many instances where new features did not behave as expected until after a period of maturing. It would be best to avoid this and simply add them manually if functionally is your goal.

answered Jul 7, 2013 at 19:45

Comments

0

You can try this one:

Sample session:

> var sets = require('simplesets')
undefined
> var mySet = new sets.Set([1, 1, 2]);
undefined
> mySet
{ _items: [ 1, 2 ] }
> mySet.size()
2
answered Jul 7, 2013 at 19:46

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.