Reputation: 121
I'm trying to create something that can detect if multiple values are in a array, this is what I tried to use, but that always returns true
row7 = [1, 1, 1, 1, 1, 1, 1, 1];
var field = [row0, row1, row2, row3, row4, row5, row6, row7];
console.log(field[0,1]); // Get the first item in the array
var needles = [1, 1, 1, 1]
console.log(needles)
var haystack = field[0,row7]
console.log(haystack)
console.log(contains(haystack,needles));
function contains(haystack, needles) {
return needles.map(function (needle) {
return haystack.indexOf(needle);
}).indexOf(-1) == -1;
}
Case true:
row 7 = [1, 1, 1, 1, 1, 1, 1, 1]
Checked for (four in a row):
needles = [1, 1, 1, 1]
And false:
row7 = [1, 1, 0, 1, 0, 0, 0, 1]
Edit:
Entire array:
/* Array containing the playing field 8 x 8
C0 C1 C2 C3 C4 C5 C6 C7
R0[0][0][0][0][0][0][0][0]
R1[0][0][0][0][0][0][0][0]
R2[0][0][0][0][0][0][0][0]
R3[0][0][0][0][0][0][0][0]
R4[0][0][0][0][0][0][0][0]
R5[0][0][0][0][0][0][0][0]
R6[0][0][0][0][0][0][0][0]
R7[0][0][0][0][0][0][0][0]
*\
var row0 = [0, 0, 0, 0, 0, 0, 0, 0],
row1 = [0, 0, 0, 0, 0, 0, 0, 0],
row2 = [0, 0, 0, 0, 0, 0, 0, 0],
row3 = [0, 0, 0, 0, 0, 0, 0, 0],
row4 = [0, 0, 0, 0, 0, 0, 0, 0],
row5 = [0, 0, 0, 0, 0, 0, 0, 0],
row6 = [0, 0, 0, 0, 0, 0, 0, 0],
row7 = [0, 0, 0, 0, 0, 0, 0, 0];
var field = [row0, row1, row2, row3, row4, row5, row6, row7];
Is there any way to achieve this using plain JS?
Thanks in advance.
Upvotes: 1
Views: 175
Reputation: 6238
I think that the easiest (not the most efficient) solution is to firstly convert both arrays into a string and then check if one string is a sub-string of another one:
function contains(array1, array2) {
if(array1 == null || array2 == null)
return false;
return array1.toString().contains(array2.toString());
}
var row7 = [1, 1, 1, 1, 1, 1, 1, 1];
var needles = [1, 1, 1, 1];
contains(row7, needles); //returns true
row7 = [1, 1, 0, 1, 0, 0, 0, 1]
contains(row7, needles); //returns false
UPDATE:
I've just realized that contains
function is not supported by all browsers. So it is better to use indexOf
i.e. return array1.toString().indexOf(array2.toString()) != -1;
Upvotes: 2
Reputation: 68433
change your contains
method to
function contains(haystack, needles)
{
return haystack.join(",").indexOf(needle.join(",")) != -1;
}
Explanation -
do a join of needle
to get "1,1,1,1"
and the join of haystack to get "1,1,1,1,1,1,1,1"
when you do indexOf
you will get 0 since needles is contained in haystack
Upvotes: 1
Reputation: 386756
You can use Array.prototype.every()
with an offset for the search.
function check(haystack, needles) {
var offset = 0;
while (offset + needles.length <= haystack.length) {
if (needles.every(function (a, i) {
return haystack[i + offset] === a;
})) {
return true;
}
offset++;
}
return false;
}
var row7 = [1, 1, 1, 1, 1, 1, 1, 1],
row8 = [1, 1, 0, 1, 0, 0, 0, 1],
needles = [1, 1, 1, 1];
document.write(check(row7, needles) + '<br>');
document.write(check(row8, needles) + '<br>');
Upvotes: 1