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.
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.
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']));
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']));
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));