23 April 2007

array functions tutorial

Recently I needed some arrays search functions for better performance so I wrote few of them. First one is simple.

`function search(wor, arr){ var exist = false; for(i=0; i< arr.length; i=i+1){ if(arr[i ]==wor){ trace("Element exist on position "+i); exist = true; } } if(!(exist)){ trace("Element don't exist in array."); }}`

In for loop we ask if wor is identical to any of array's elements. Note that we use == not = (common mistake). Boolean variable exists is responsible for finding our word in array. If word multiple times in array, all positions will be find. Second function is almost the same. Difference is that this one returns true or false. True if wor is in arr, false otherwise. It goes like this.

`function searchB(wor, arr){ var exist = false; for(i=0; i< arr.length; i=i+1){ if(arr[i]==wor){ return true; exist = true; } } if(!(exist)){ return false; }}`
This function will end on first appearence of wor in arr. If wor don't exist in arr, function will return false. You can test these functions like this:

`_root.onMouseDown=function(){ planets = new Array("Merkur", "Venus", "Earth", "Mars"); habitable = "Earth"; what = search(habitable, planets); trace(what);}`
Similar for searchB function.

Third function is called searchCount, simply beacuse it counts number of wor in array. It goes something like this:

`function searchCount(wor, arr){ var count = 0; for(i=0; i< arr.length; i=i+1){ if(arr[i ]==wor){ count += 1; } } return count;}`
Another function is union. If you have two arrays, union will return new array which consist of word that exists in both arrays.

`function union(arr1, arr2){ var arr3 = new Array(); count = 0; for(i=0; i< arr1.length; i=i+1){ for(j=0; j< arr2.length; j=j+1){ if(arr1[i ]== arr2[ j]){ arr3[count ] = arr1[ i]; count+=1; } } } return arr3;}`
One more important thing. Data type in these functions do not have to be String, it can be any type. For more strict evaluation, you can put === instead of ==.

note: this post have been moved from flanture.blog.com