简体   繁体   中英

Search an array of arrays JavaScript

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);
    }
}

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)); 

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;
    });
}

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;
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM