2

Is there a way to use arrays as values in a javascript Set?

Example:

s = new Set()
s.add([1,2])
s.has([1,2]) // -> false
s.add(1)
s.has(1)  // -> true

Presumably, the case with the array returns false because it's looking at the references and not the actual values of the arrays. Is there a way to do this operation so that s.has([1,2]) returns true?

2 Answers 2

1

You can use json as key.

s = new Set()
s.add(JSON.stringify([1,2]))
s.has(JSON.stringify([1,2])) // true
Sign up to request clarification or add additional context in comments.

1 Comment

This works, but I'm just going to wait a bit to see if there's any other ideas before accepting it. More specifically, I'm curious if there's something similar to python's tuple which is passed by value rather than reference.
1

You have to be carefull here, cause Set.has compares objects (here arrays) by reference, so it should look like this:

var a = [1,2]; var s = new Set([a]); s.has(a); // -> true

That will work, but i would wrap Set with my own prototype for not iterating each time through set:

           function compareByValue(pool, needle){
                var search = [];
                pool.forEach(function(value) {
                    search.push(value.toString());
                });
                return search.indexOf(needle.toString()) !== -1;
            }
            compareByValue(s, [1,2]); // -> true

1 Comment

Right, but I want to check by value.

Your Answer

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.