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???"**`);
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.
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).
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.
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.
/**
* 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] + '].');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With