I have a multi-dimensional array, and i want to find a string in that array that the user inputs. And i want to store it's index(both of them, like of the string is at arr[a][b]
, i need both the values of a
and b
.
For example, i have an array as following and want to find the word "scar", how can i get it?
var arr=[["hey","oh"],["scar","tissue"],["other","side"]];
I have tried the following block :
var a;
var b;
for (var z = 0; z < arr.length; z++) {
for (var i = 0; i < 2; i++) {
if (arr[z][i] === "scar") {
b = z;
a = i;
}
}
}
I tried searching and researching the question but couldn't find one.
Thanks in advance.
You can search your string in many way
using a nested for-for
for (a = 0; a < arr.length; a++){
for (b=0; b < arr[a].length; b++){
if (arr[a][b] == mySearch){
return true;
}
}
}
using a nested forEach
var found = false;
arr.forEach(function(a) {
a.forEach(function(b) {
if (b == wordToFind) {
found = true;
}
});
});
return found;
you can loop each subarray and then with the function indexOf()
check if the required index is found:
var arr = [["hey","oh"], ["scar","tissue"], ["other","side"]]; function get_index_of_string(my_array, mystring) { var a = 0; var results = []; var b, subarray; for (var arrayIndex in my_array) { subarray = my_array[arrayIndex]; var search = subarray.indexOf(mystring) if (search != -1){ a++; b = search; } } results[0] = a; results[1] = b; return results; } var results = get_index_of_string(arr,"scar"); if (results[0] != -1 && results[1] != -1) { alert("String is found in the " + results[0] + " subarray in the " + results[1] + " index"); } else{ alert("String is not found"); }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.