I\'m working in JavaScript. I\'d like to store a list of unique, unordered string values, with the following properties:
In ES6 version of Javascript you have built in type for set (check compatibility with your browser).
var numbers = new Set([1, 2, 4]); // Set {1, 2, 4}
To add an element to the set you simply use .add()
, which runs in O(1)
and either adds the element to set (if it does not exist) or does nothing if it is already there. You can add element of any type there (arrays, strings, numbers)
numbers.add(4); // Set {1, 2, 4}
numbers.add(6); // Set {1, 2, 4, 6}
To check the number of elements in the set, you can simply use .size
. Also runs in O(1)
numbers.size; // 4
To remove the element from the set use .delete()
. It returns true if the value was there (and was removed), and false if the value did not exist. Also runs in O(1)
.
numbers.delete(2); // true
numbers.delete(2); // false
To check whether the element exist in a set use .has()
, which returns true if the element is in the set and false otherwise. Also runs in O(1)
.
numbers.has(3); // false
numbers.has(1); // true
In addition to methods you wanted, there are few additional one:
numbers.clear();
would just remove all elements from the setnumbers.forEach(callback);
iterating through the values of the set in insertion ordernumbers.entries();
create an iterator of all the valuesnumbers.keys();
returns the keys of the set which is the same as numbers.values()
There is also a Weakset which allows to add only object-type values.