Reputation: 1917
Here is my array:
var array = [[0,1,0,1,0,1,0,1],
[1,0,1,0,1,0,1,0],
[0,1,0,1,0,1,0,1],
[0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0],
[2,0,2,0,2,0,2,0],
[0,2,0,2,0,2,0,2],
[2,0,2,0,2,0,2,0]];
How can I search in this array of arrays using just javascript? For example, how would I search if there is a 3 in this array of arrays?
javascript search array of arrays didn't help me, I might be attempting it wrong:
var result;
for( var i = 0, len = model.board.length; i < len; i++ ) {
if( model.board[i][0] == 3 ) {
result = selected_products[i];
alert("found a 3 " + result);
}
}
Upvotes: 0
Views: 236
Reputation: 19274
Loop through each sub-list in array
, then loop through each item in that sub-list:
var array = [[0,1,0,1,0,1,0,1],
[1,0,1,0,1,0,1,0],
[0,1,0,1,0,1,0,1],
[0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0],
[2,0,2,0,2,0,2,0],
[0,2,0,2,0,2,0,2],
[2,0,2,0,2,0,2,0]];
function search(arr, item){
for(var i = 0; i < array.length; i++){
var sub = array[i];
for(var j = 0; j < sub.length; j++){
if(sub[j] == item){
return true;
}
}
}
return false;
}
document.write("Search for 3: " + search(array, 3), "<br>");
document.write("Search for 2: " + search(array, 2));
Upvotes: 2
Reputation: 14371
The currently accepted answer will only work on arrays with one array in it. This uses some tricks to get the values. This even works if the numbers are strings. And gets all numbers
var array = [[0,1,0,1,0,1,0,1],
[1,0,1,0,1,0,1,0],
[0,1,0,1,0,1,0,1],
[0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0],
[2,0,2,0,2,0,2,0],
[0,2,0,2,0,2,0,2],
[2,0,2,0,2,0,2,0]];
function searchForNum(ar, num) {
return ar.toString().match(/[\d\-\.]+/g).indexOf(''+num) > -1;
}
Upvotes: 0
Reputation: 43728
There are many ways, but here's one:
Note that some
will short circuit as soon as true
is returned.
//returns true if 3 is found or false otherwise
array.some(function (arr) {
return arr.indexOf(3) !== -1;
});
This pattern is easy to recurse if you wish to extend this to n-dimensional structures – Paul S
Here's what he meant:
searchArray([[1, 2, 3], [4, 5, [6, 7, [8]]]], 8);
function searchArray(arr, val) {
return arr.some(function (item) {
return Array.isArray(item)? searchArray(item, val) : item === val;
});
}
Upvotes: 1