开发者

Cleanest way to search a 2D array?

The easiest way I开发者_StackOverflow 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;

Cleanest way to search a 2D array?

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜