Rohit Chopra Rohit Chopra - 5 months ago 24
Javascript Question

compare 2d array with 1d array in javascript

var player1=[t1,t2,t3,t5,t7];
var winmoves=[[t1,t2,t3],[t4,t5,t6],[t7,t8,t9],[t1,t4,t7],[t2,t5,t8],[t3,t6,t9],[t1,t5,t9],[t3,t5,t7]];

else if (moves>=3 && moves<=9) {
moves+=1;
if (turn==1) {
var i=0;
turn=2;
x.innerHTML="<img src='x.png'/>";
player1.push(x.id);
while(i<=moves){
if (winmoves[i] in player1) {
alert("player1 wins");
document.getElementById("player1").innerHTML=1;
}
i+=1;
}
}


i have 1d array player1 and 2d array winmoves in javascript and i want to check that w[0]'s all values are present in p and so on for w[1],w[2],etc.
if condition with
(winmoves[i] in player1)
is not working.
i don't know if i am writing this write.
help me guys i am stuck here how can i do so.

Answer

I would simply do this with a simple invention of Array.prototype.intersect() and the rest is such a straightforward single liner.

Array.prototype.intersect = function(a) {
  return this.filter(e => a.includes(e));
};

var player1 = ["t1","t2","t3","t5","t7"],
   winmoves = [["t1","t2","t3"],["t4","t5","t6"],["t7","t8","t9"],["t1","t4","t7"],["t2","t5","t8"],["t3","t6","t9"],["t1","t5","t9"],["t3","t5","t7"]];
   filtered = winmoves.filter(a => a.intersect(player1).length == a.length);
     mapped = winmoves.map(a => a.intersect(player1).length == a.length);
console.log(filtered);
console.log(mapped);

OK we have a generic Array method which finds the intersection of two arrays. (inbetween the array it's called upon and the one provided as argument) It's basically a filter checking each item of first array to see whether it is included in the second array. So we filter out the items exist in both arrays.

To obtain the filtered array we utilize Array.prototype.filter() again. This time our first array is winmoves which includes arrays that we will check for each the intersection with player1 array. If the intersection length is equal to winmove's item's length that means all elements of winmove's item is existing in the player1 array. So we return that array item to the filtered.

Specific to your case without using an intersect method you can utilize Array.prototype.every() as follows;

var player1 = ["t1","t2","t3","t5","t7"],
   winmoves = [["t1","t2","t3"],["t4","t5","t6"],["t7","t8","t9"],["t1","t4","t7"],["t2","t5","t8"],["t3","t6","t9"],["t1","t5","t9"],["t3","t5","t7"]];
   filtered = winmoves.filter(a => a.every(e => player1.includes(e)));
     mapped = winmoves.map(a => a.every(e => player1.includes(e)));
console.log(filtered);
console.log(mapped);