Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cleanest way to search a 2D array?

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?

like image 511
JCOC611 Avatar asked Feb 06 '11 23:02

JCOC611


2 Answers

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
like image 60
Neil Avatar answered Oct 21 '22 23:10

Neil


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;

enter image description here

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.

like image 2
Myles Gray Avatar answered Oct 21 '22 22:10

Myles Gray