Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Effective ways of finding an element in a Javascript array

I am using an array with titles. Each titles index corresponds to an id in a database which contains html for that given title.

Lets say I have a string which contains one of the titles.

title = "why-birds-fly";
titles[] // an array which contains all the titles

To use the string "title" to get the corresponding id I could do:

for (i = 0; i < titles.length-1; i++) {
  if (titles[i] == title)
    return i+1;
}

Another method I could use is to create an associative array together with the titles array which is the exact opposite of titles. That is, it uses the string as an index and returns the number.

titles_id {blah:0,why-birds-fly:1,blah2:2}

I could then access the ID by:

return titles_id[title]+1;

What would be most effective considering CPU, Memory, etc?

Also, please let me know if my logic is all wrong.

Thanks Willem

like image 545
Willem Avatar asked Mar 13 '09 10:03

Willem


1 Answers

The linear search approach has a complexity of O(n), and I think the worst case for the associative array approach is probably O(log n), (the best case maybe O(1) if the JS engine is using hashes and getting no collisions). It will depend on how a JS engine typically implements associative arrays/objects, but you can be sure it will beat O(n).

So, the second approach will be faster, but will of course use more memory. This is a very typical trade off, gaining more speed, but using more memory, and only you can decide whether you want to make that trade.

like image 128
Paul Dixon Avatar answered Oct 20 '22 00:10

Paul Dixon