The easiest way I could think of is a for loop:
var arr=[["hey","oh"],["scar","tissue"],["other","side"]];
var query="scar";
for(var z=0;z<arr.length;z++){
if(arr[z].indexOf(query) !== -1){
//Found
break;
}
}
Is there any other way to search for a string in a 2D array?
var arr = [["hey","oh"],["scar","tissue"],["other","side"]];
var flat = [].concat.apply([], arr);
var col = flat.indexOf(query);
var row = -1;
if (col != -1) // found, now need to extract the row
while (arr[++row].length <= col) // not this row
col -= arr[row].length; // so adjust and try again
You could do this:
var arr=[["hey","oh"],["scar","tissue"],["other","side"]];
arr.sort();
arr.join();
To sort alphabetically then,
A binary search works by looking at the middle value in the array then seeing if the searched for keyword/number is > or < that value and thus dividing the array in half, then splits the remaining in half again and continues until the searched value is found;
To implement a binary search please read here: http://www.timlin.net/csm/cis111/Chapter10.pdf
Slides 52-56 on...
This method theoretically makes your search exponentially faster.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With