The cleanest way to find 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 find a string in a 2D array?

+5
source share
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
+11
source

You can do it:

var arr=[["hey","oh"],["scar","tissue"],["other","side"]];

arr.sort();
arr.join();

To sort alphabetically,

Binary search works by looking at the average value in the array, and then looking if the search keyword / number> or <is the value and thus dividing the array in half, then again dividing the remaining in half and continuing until it finds value;

enter image description here

To implement binary search, read here: http://www.timlin.net/csm/cis111/Chapter10.pdf

52-56 ...

.

+2

All Articles