Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing arrays in ES6 Set and accessing them by value

Is there a simple way to verify that an ES6 Set contains a value that is a particular array? I'd like a solution that doesn't require me to use a reference:

var set = new Set();

var array = [1, 2];
set.add(array);
set.has(array); // true

set.add([3, 4]);
set.has([3, 4]); // false

So far my solution is to store everything as a string, but this is annoying:

set.add([3, 4].toString());
set.has([3, 4].toString()); // true
like image 380
djfdev Avatar asked Apr 21 '15 00:04

djfdev


People also ask

Can Set hold arrays?

A Set works on objects and primitives and is useful for preventing identical primitives and re-adding the same object instance. Each array is their own object, so you can actually add two different arrays with the same values. Additionally, there's nothing to prevent an object from being changed once in a set.

How do you access an array element?

Access Array Elements You can access an array element by referring to its index number. The indexes in NumPy arrays start with 0, meaning that the first element has index 0, and the second has index 1 etc.

How do you access an array inside an array?

To access an element of the multidimensional array, you first use square brackets to access an element of the outer array that returns an inner array; and then use another square bracket to access the element of the inner array.

Are arrays pass by value JavaScript?

Primitive data types such as string, number, null, undefined, boolean, are passed by value while non-primitive data types such as objects, arrays, and functions are passed by reference in Javascript.


1 Answers

No there is not.

A Set works on objects and primitives and is useful for preventing identical primitives and re-adding the same object instance.

Each array is their own object, so you can actually add two different arrays with the same values.

var set = new Set();
set.add([3, 4]);
set.add([3, 4]);
console.log(set.size);//2

Additionally, there's nothing to prevent an object from being changed once in a set.

var set = new Set();
var a1 = [3, 4];
var a2 = [3, 4];
set.add(a1);
set.add(a2);
a2.push(5);
for (let a of set) {
    console.log(a);
}
//Outputs:
// [3, 4]
// [3, 4, 5]

A set does not have a mechanism for checking the values of objects in a set. Since the value of an object could change at any time, it wouldn't be much more efficient than simply looping over them yourself.

The functionality you are looking has been kicked around in various ECMAScript proposals, however it does not appear to be coming anytime soon.

like image 72
Alexander O'Mara Avatar answered Nov 09 '22 11:11

Alexander O'Mara