How to check if an array contains another array?

后端 未结 6 1800
后悔当初
后悔当初 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 16:55

    For those who are interested in finding an array inside another and get back an index number, here's a modified version of mohamed-ibrahim's answer:

    function findArrayInArray(innerArray, outerArray) {
        const innerArrayString = JSON.stringify(innerArray);
        let index = 0;
        const inArray = outerArray.some(function (element) {
            index ++;
            return JSON.stringify(element) === innerArrayString;
        });
        if (inArray) {
            return index - 1;
        } else {
            return -1;
        }
    }
    findArrayInArray([1, 2, 3], [[3, .3], [1, 2, 3], [2]]); // 1
    findArrayInArray([1, 2, 3], [[[1], 2, 3], [2]]) // -1
    

    This function returns the index of the array you are searching inside the outer array and -1 if not found.

    Checkout this CodePen.

提交回复
热议问题