2D Array Search

by nevkatz

HTML

<div id="root">

</div>

JavaScript

/* searches a 2D array */
/* returns the indices of the first matching value */
function search2D(arr,target) {
     // iterate through each row of the array
     for (var i = 0; i < arr.length; ++i) {
        let row = arr[i];
        // iterate through each cell of a row
        for (var j = 0; j < row.length; ++j) {
            let cell = row[j];
            // if we have a match
            if (cell == target) {
               // return the indices in an object
               return {
                 x:j,
                 y:i
               };
            }
        }
     }
     return null;
}
// a test of the function.
function init() {
  // create a test array. 
  let my_arr = [
    ['apples','bananas'],
    ['asparagus','beets']
  ];
  // run the function to get the indices.
  let c = search2D(my_arr,'bananas');
  // grab the output element.
  let root = document.getElementById('root');
  // print the result.
  root.textContent = `${c.x},${c.y}`;
}
init();