0

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

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

2 Comments

This pattern is easy to recurse if you wish to extend this to n-dimensional structures, too
@PaulS. I added a recursive example.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.