To find Index of Multidimensional Array in Javascript
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] + '].');
this example seems to work well also with IRREGULAR multidimentional array:
function findIndex(valueToSearch, theArray, currentIndex) {
if (currentIndex == undefined) currentIndex = '';
if(Array.isArray(theArray)) {
for (var i = 0; i < theArray.length; i++) {
if(Array.isArray(theArray[i])) {
newIndex = findIndex(valueToSearch, theArray[i], currentIndex + i + ',');
if (newIndex) return newIndex;
} else if (theArray[i] == valueToSearch) {
return currentIndex + i;
}
}
} else if (theArray == valueToSearch) {
return currentIndex + i;
}
return false;
}
var a = new Array();
a[0] = new Array(1, 2, 3, 4, 5);
a[1] = 'ciao';
a[2] = new Array(new Array(6,7),new Array(8,9),10);
var specificIndex = findIndex('10', a);
i wrote this speedly so everyone is invited to improve this function!
p.s. now the function returns a STRING value with all indexes separated by comma, you can simply edit it to returns an object
On jsfiddle
function indexOf2d(arr, val) {
var index = [-1, -1];
if (!Array.isArray(arr)) {
return index;
}
arr.some(function (sub, posX) {
if (!Array.isArray(sub)) {
return false;
}
var posY = sub.indexOf(val);
if (posY !== -1) {
index[0] = posX;
index[1] = posY;
return true;
}
return false;
});
return index;
}
console.log(indexOf2d(array, 50));