I have a list of a few thousand integer keys. The only thing I need to do with this list is say whether or not a given value is in the list.
For C# I would use a HashSet
to make that look-up fast. What's the JavaScript equivalent?
Minimal support level: IE 9+, jQuery (current)
Actually JavaScript provides a Set object, fairly simple to use:
var set = new Set(); set.add(1); set.add(2); set.has(1) // true
Unfortunately, it is not compatible with IE9.
Under the hood, the JavaScript Object is implemented with a hash table. So, your Key:Value
pair would be (your integer):true
A constant-time lookup function could be implemented as:
var hash = { 1:true, 2:true, 7:true //etc... }; var checkValue = function(value){ return hash[value] === true; }; checkValue(7); // => true checkValue(3); // => false
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With