0

Using JavaScript in Node.Js v11, I encounter the problem, that I am trying to convert a string array (featuring duplicate entries) to a Set Object - in order to get rid of the duplicate entries - like this:

var arr = ["book", "author", "lines", "book"]; 
var unique = new Set(arr); //hoping for "book", "author", "lines" entries
console.log(JSON.stringify(unique));  //unique is empty!?

For some strange reason, my unique object remains empty after conversion. What am I missing?

EDIT: I marked an answer as well as approved a request to mark this a duplicated question due to the fact that my problem was not associtated with the result object being empty but using the wrong method to output its entries (JSON.stringify) as correctly pointed out by many contributors here.

Igor P.
  • 1,407
  • 2
  • 20
  • 34

3 Answers3

1

Based on this JSON.stringify doesn't directly work with sets because the data stored in the set is not stored as properties.

But you can convert to array:

var arr = ["book", "author", "lines", "book"];
        var unique = new Set(arr); //hoping for "book", "author", "lines" entries
        console.log(JSON.stringify([...unique]));

Or removed JSON.stringify .

Alireza Ahmadi
  • 8,579
  • 5
  • 15
  • 42
0

Stringify doesn't work on sets directly - see this answer for a workaround: https://stackoverflow.com/a/31190928/10922876

Sully
  • 395
  • 3
  • 7
0

JSON.stringify doesn't work on sets as the Set object is not in the form of JSON (i.e. key value pairs).

To print the set you can do the following:

var arr = ["book", "author", "lines", "book"]; 
var unique = new Set(arr); //hoping for "book", "author", "lines" entries
console.log(unique); //  {"book", "author", "lines"}
Alireza Ahmadi
  • 8,579
  • 5
  • 15
  • 42
Atharva Sharma
  • 295
  • 1
  • 9