Reputation: 5962
I have 3 arrays, I want to check if any element of subarray in mainArray is exist - then it should return true.
I have tried this, but it is returning true only if mainArray containing all the item of sub array.
MY js:
var sub1 = ["0", "10"];
var sub2 = ["18", "3", "13", "4"];
var mainArr = ["0", "1", "5", "8", "9", "10"];
if (containsChk(sub1, mainArr)) {
alert('yes');
} else {
alert('no');
}
function containsChk(sub, main) {
for (var i = 0, len = sub.length; i < len; i++) {
if ($.inArray(sub[i], main) == -1) return false;
}
return true;
}
Upvotes: 0
Views: 101
Reputation: 9637
try
var sub1 = ["0", "10"];
var sub2 = ["18", "3", "13", "4"];
var mainArr = ["0", "1", "5", "8", "9", "10"];
if (containsChk(sub1, sub2, mainArr)) {
alert('yes');
} else {
alert('no');
}
function containsChk(sub, sub2, main) {
var isIn = false;
for (var i = 0, len = sub.length; i < len; i++) {
if ($.inArray(sub[i], main) != -1) {
isIn = true;
break;
}
}
if (!isIn) {
for (var i = 0, len = sub2.length; i < len; i++) {
if ($.inArray(sub2[i], main) != -1) {
isIn = true;
break;
}
}
}
return isIn;
}
Upvotes: 0
Reputation: 1758
You should just use array.indexOf()
(http://www.w3schools.com/jsref/jsref_indexof_array.asp).
for (var i = 0; i < sub1.length; i++)
if (mainArray.indexOf(sub1[i]) != -1)
return true;
return false;
Upvotes: 5