2

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:

  1. creating an array and, for each new item you push, first check if _.indexOf(array, newItem) == -1
  2. creating a hash, with all values as true, such as {key1: true, key2: true}, then _.keys(hash)
  3. 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?

1 Answer 1

6

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 just O(n).

The third depends on how efficient uniq() is. For instance, it might well just be an implementation of method 2.

Sign up to request clarification or add additional context in comments.

1 Comment

At small scales (less than 50 keys per object), the first solution seems to be more than 3x as fast as the second in node: gist.github.com/4633028.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.