1

i need to find whether a array contains an another array or not ..

var array  = ['a',['b','c','d']];

im unable find this. so can anyone please help me out of this.

thank you.

Nani
  • 446
  • 7
  • 24
  • 4
    Possible duplicate of [How do I check if an array includes an object in JavaScript?](https://stackoverflow.com/questions/237104/how-do-i-check-if-an-array-includes-an-object-in-javascript) – Clément Denoix Nov 18 '17 at 09:48

3 Answers3

3

You could iterate the elements with Array#some and check if the element is an array with Array.isArray.

function containsArray(array) {
    return array.some(item => Array.isArray(item));
}

console.log(containsArray(['a', ['b', 'c', 'd']]));
console.log(containsArray(['a', 'b', 'c', 'd']));

ES5

function containsArray(array) {
    return array.some(function (item) {
        return Array.isArray(item);
    });
}

console.log(containsArray(['a', ['b', 'c', 'd']]));
console.log(containsArray(['a', 'b', 'c', 'd']));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • thx @Nina Scholz thq for replaying.. its working fine....could you please explan it. what is 'some' & 'a' in "array.some(a => Array.isArray(a))" – Nani Nov 18 '17 at 10:10
  • it is a short version of a callback with an [arrow function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions). the function is called for every item of the array and that item gets checked. if the check returns `true`, the iteration is stopped, because it searches for a single [truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy) return value. – Nina Scholz Nov 18 '17 at 10:16
0

You can try this way :

var array  = ['a',['b','c','d']];

function contains(a, toFind) {
    for (var i = 0; i < a.length; i++) {
        if (equalArray(a[i], toFind)) {
            return true;
        }
    }
    return false;
}
function equalArray(a, b) {
    if (a.length === b.length) {
        for (var i = 0; i < a.length; i++) {
            if (a[i] !== b[i]) {
                return false;
            }
        }
        return true;
    } else {
        return false;
    }
}

alert(contains(array, ['b', 'c', 'd']));
Vincent Decaux
  • 9,857
  • 6
  • 56
  • 84
0

In case you don't just need a boolean (true/false) answer, you could also use Array find() Method along with Array.isArray() to return the Inner Array as well. See the below example.

EDIT In case you have an Array with more than one Inner Arrays then the Array filter() Method would be more appropriate.

var arr = [3, 10, 18, [3, 4, 5, 8], 20];
var arr2 = [3, 10, 18, [3, 4, 5, 8], [1, 2], 20];
var arr3 = [1, 2, 3, 4];
function check(v) {
    return (Array.isArray(v))?v:false;
}
console.log(arr.find(check));
console.log(arr2.filter(check));

console.log(arr3.find(check));
console.log(arr3.filter(check));