If your names are unique, use an object hash, the lookup time is O(1).
You could structure it like:
var lookup =
{
jame: 1,
hey: 3,
el: 2,
'a name with spaces': 87
};
var code = lookup['jame']; // gives 1
Note that:
var code = lookup['jaem']; // gives undefined
Also note that the lookup keys (the names) need to follow valid JavaScript variable naming conventions, otherwise you have to place them in quotes, double " " or single ' ', your choice
If you have to have an array of objects for your autocomplete to work, then you might have to use both, but generate the lookup from the array, like:
var lookup = {};
data.forEach(function(index)
{
lookup[data[index].name] = data[index].code;
});
A few questions,
- How big is your array of data?
- Have you timed just the lookup time?
- If your list is small, are you doing anything else in your code that shouldn't be in the lookup routine?
- Is this the jQuery UI autocomplete you are using?
To optimize what you have a for
loop would be much faster than a for in
loop.
Also, I suspect your are using autocomplete so you get n
results for each prefix the user has typed, in which case, the lookup will not work, therefore ... depending on your use case and the desired outcome, you might be better served using a different data structure completely ... maybe a trie
Here is one that was prepared earlier. The author of JQuery has some ideas as well.