What is the optimal way to get unique strings in an array? There are times when it makes sense to do it one of many ways, here are 3:
- creating an array and, for each new item you push, first check if
_.indexOf(array, newItem) == -1 - creating a hash, with all values as
true, such as{key1: true, key2: true}, then_.keys(hash) - pushing all items in the array, then running
keys = _.uniq(keys)
The above code is using underscore.js helpers.
Having knowledge of the internals of JavaScript constructs/vm’s, and some formal algorithms knowledge, would probably make this a no brainer but I’m not there yet. I’m sure it differs from browser to browser (and node), but maybe there is a preferred approach. Any ideas?
The first solution has to loop through every element of the array, for each element of the array. That makes a complexity of
O(n²).The second is probably the best, because it only loops through the array, then loops through the keys. That’s basically
O(2n), which is justO(n).The third depends on how efficient
uniq()is. For instance, it might well just be an implementation of method 2.