-1

How can I see if the array movesByX has the values but is not in the order as displayed in the checkWinningMoves fucntion how can make sure it works properly and executes the function

function checkWinningMoves() {
   if (movesByX == ["box1", "box2", "box3"]) {
       console.log("X is the winner")
   }
}
let movesByX = [ "box2", "box1", "box3"]

checkWinningMoves();
Sebastian Richner
  • 782
  • 1
  • 13
  • 21
Jesse
  • 58
  • 1
  • 5
  • 3
    You can't compare arrays this way, equality is evaluated by reference, not shape/value. see: [How to compare arrays in JavaScript?](https://stackoverflow.com/questions/7837456/how-to-compare-arrays-in-javascript) – pilchard Jul 19 '21 at 10:56

1 Answers1

0

I have written a Function, that will check if all the winning moves are present in movesByX irrespective of order. It uses a for loop, and array's includes method, that checks if an element is present in array or not.

function checkWinningMoves() {
  if (checkElem(movesByX)) {
    console.log("X is the winner")
  } else{
    console.log("X is not the winner");
  }
}

let movesByX = ["box2", "box1", "box3"]
checkWinningMoves();

movesByX = ["box2", "box4", "box3"]
checkWinningMoves();


function checkElem(arr) {
  let a = ["box1", "box2", "box3"];
  let out = false;

  for(var i = 0;i<a.length; i++){
    if(arr.includes(a[i])){
      out = true;
    } else{
      out = false;
      break;
    }
  }
    return out;
  }
TechySharnav
  • 4,869
  • 2
  • 11
  • 29