Home > Net >  To get a truthy condition(array) from a nested array, for now the function returns boolean value tru
To get a truthy condition(array) from a nested array, for now the function returns boolean value tru

Time:03-29

The checkWin function returns true when an array which are index numbers have a speicified symbol on another Array's indexes. How to retrieve the "cond"(array) which results in true from the nested winConditions array ?

Symbols get populated using the click event listener.

The expected result should be, if .some(cond) becomes true then return that cond for eg. if symbol "X" is present on [0, 1, 2] then return this array

let testArray = Array(9).fill("") 
 
  const winConditions = [
    [0, 1, 2],
    [3, 4, 5],
    [6, 7, 8],
    [0, 3, 6],
    [1, 4, 7],
    [2, 5, 8],
    [0, 4, 8],
    [2, 4, 6],
  ];

  let xValue = "X";
  let oValue = "O";

function checkWin(value, array) {
    return winConditions.some((cond) =>
        cond.every((index) => array[index] == value));
}

console.log(checkWin(xValue, testArray));
console.log(checkWin(oValue, testArray));

CodePudding user response:

You can use .find() instead of .some(), this will return the first array that the .every() callback returns true for. You can use this array to determine if there was a win or not for a particular player:

const testArray = Array(9).fill("");
testArray[3] = testArray[4] = testArray[5] = "O"; // test winning position
const winConditions = [
  [0, 1, 2],
  [3, 4, 5],
  [6, 7, 8],
  [0, 3, 6],
  [1, 4, 7],
  [2, 5, 8],
  [0, 4, 8],
  [2, 4, 6],
];

const xValue = "X";
const oValue = "O";

function getWinPos(value, array) {
  return winConditions.find((cond) =>
    cond.every((index) => array[index] == value)
  );
}

const xWinPos = getWinPos(xValue, testArray);
const oWinPos = getWinPos(oValue, testArray);

if(xWinPos) { // found a winning position row/col/diag for "X"
  console.log(xWinPos);
} else if(oWinPos) { // found a winning row/col/diag for "O"
  console.log(oWinPos);
}

  • Related