How to check if an array contains another array?

后端 未结 6 1796
后悔当初
后悔当初 2020-11-28 16:36

I needed 2d arrays, so I made nested array since JavaScript doesn\'t allow them.

They look like that:

var myArray = [
      [1, 0],
      [1, 1],
            


        
6条回答
  •  时光取名叫无心
    2020-11-28 17:10

    A nested array is essentially a 2D array, var x = [[1,2],[3,4]] would be a 2D array since I reference it with 2 index's, eg x[0][1] would be 2.

    Onto your question you could use a plain loop to tell if they're included since this isn't supported for complex arrays:

    var x = [[1,2],[3,4]];
    var check = [1,2];
    function isArrayInArray(source, search) {
        for (var i = 0, len = source.length; i < len; i++) {
            if (source[i][0] === search[0] && source[i][1] === search[1]) {
                return true;
            }
        }
        return false;
    }
    console.log(isArrayInArray(x, check)); // prints true
    

    Update that accounts for any length array

    function isArrayInArray(source, search) {
        var searchLen = search.length;
        for (var i = 0, len = source.length; i < len; i++) {
            // skip not same length
            if (source[i].length != searchLen) continue;
            // compare each element
            for (var j = 0; j < searchLen; j++) {
                // if a pair doesn't match skip forwards
                if (source[i][j] !== search[j]) {
                    break;
                }
                return true;
            }
        }
        return false;
    }
    console.log(isArrayInArray([[1,2,3],[3,4,5]], [1,2,3])); // true
    

提交回复
热议问题