Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

To find Index of Multidimensional Array in Javascript

I have created a multidimensional array in JavaScript and I want to find the exact index of specific value. That value will be user input.

var array = [];
var k = 0;
for (var i = 0; i < 10; i++) {
  array[i] = [];
  for (var j = 0; j < 100; j++) {
    k = k + 1
    array[i].push(k);
  }
}
var index = array.indexOf(`**"What to insert here???"**`);
like image 715
Rayon Avatar asked Apr 19 '13 10:04

Rayon


People also ask

How do you find the index of an element in an array in JS?

Array.prototype.indexOf() The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.

Does indexOf work on 2D array?

You cannot use indexOf to do complicated arrays (unless you serialize it making everything each coordinate into strings), you will need to use a for loop (or while) to search for that coordinate in that array assuming you know the format of the array (in this case it is 2d).

How do you find the index of an array of objects?

To find the index of an object in an array, by a specific property: Use the map() method to iterate over the array, returning only the value of the relevant property. Call the indexOf() method on the returned from map array. The indexOf method returns the index of the first occurrence of a value in an array.

How do you find the index of an object in an array in TypeScript?

The Array. indexOf() is an inbuilt TypeScript function which is used to find the index of the first occurrence of the search element provided as the argument to the function.


1 Answers

JSFiddle

/**
 * Index of Multidimensional Array
 * @param arr {!Array} - the input array
 * @param k {object} - the value to search
 * @return {Array} 
 */
function getIndexOfK(arr, k) {
  for (var i = 0; i < arr.length; i++) {
    var index = arr[i].indexOf(k);
    if (index > -1) {
      return [i, index];
    }
  }
}

// Generate Sample Data
var k = 0;
var array = [];
for (var i = 0; i < 10; i++) {
  array[i] = [];
  for (var j = 0; j < 100; j++) {
    k = k + 1;
    array[i].push(k);
  }
}
var needle = 130;
var result = getIndexOfK(array, needle);
console.log('The value #' + needle + ' is located at array[' + result[0] + '][' + result[1] + '].');
like image 200
Du D. Avatar answered Oct 14 '22 21:10

Du D.