juniper-
juniper-

Reputation: 6572

Javascript Set with Array Values

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?

Upvotes: 2

Views: 154

Answers (2)

Andre
Andre

Reputation: 29

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

Upvotes: 1

Tarwirdur Turon
Tarwirdur Turon

Reputation: 781

You can use json as key.

s = new Set()
s.add(JSON.stringify([1,2]))
s.has(JSON.stringify([1,2])) // true

Upvotes: 1

Related Questions