Answer the question
In order to leave comments, you need to log in
What is the JavaScript way to check if one array is completely contained in another without using a double loop?
Advise a way to check the complete occurrence of one array in another, regardless of the order of the elements in JavaScript without using a double loop - actually the question.
While I have this
var equalTags = 0;
for(var a=0; a<tag.length; a++) {
for(var b=0; b<tagsOff.length; b++) {
if (tag[a]==tagsOff[b]) {
equalTags ++;
}
}
if (equalTags == tag.length) {
console.log(i+' - off - '+equalTags);
} else {
console.log(i+' - on - '+equalTags);
}
}
Answer the question
In order to leave comments, you need to log in
If @egor_nullptr understood you correctly, and you need to check that the array b contains at least one instance of each element of the array a, then I propose this solution:
Array.prototype.hasAll = function(a) {
var hash = this.reduce(function(acc, i) { acc[i] = true; return acc; }, {});
return a.every(function(i) { return i in hash; });
};
Array.prototype.diff = function(a) {
return this.filter(function(i) {return !(a.indexOf(i) > -1);});
};
[5,3,4].diff([1,2,3,4,5,6])
// => [], и это означает полное вхождение
If undersore is connected, then, for example, like this:
http://underscorejs.ru/#without
// Вернет массив a без элементов из массива a
if (_.without.apply(this, b.unshift(a))) {
}
If it is performance that is important, then the problem is similar to the problem of checking the occurrence of a substring. To do this, you can use the Knuth-Morris-Pratt or Rabin-Karp algorithms.
Usually I do such checks through array intersections (or they gave you the diff function). It won't work without nested loops, because in fact both indexOf and array.filter are loops. Unless you can interrupt the execution of the loop as soon as there is an element that does not fall into another array.
function isSame(a, b) {
if (a.length > b.length) {
b = [a, a = b][0]; //swap
}
for(var i = 0, length = a.length;i<length;i++) {
if (-1 === b.indexOf(a[i])) {
return false;
}
}
return true;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question