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.

3
  • Set is not strigifiable. Commented Jul 8, 2021 at 13:41
  • Voting to close as duplicate: JSON stringify a Set Commented Jul 8, 2021 at 14:40
  • Thanks, I already marked an answer that helped me out. Commented Jul 8, 2021 at 14:42

3 Answers 3

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 .

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

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"}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.