1

My problem is about comparing the values of two different arrays, not to know if they are equal, but if a value in array A exists in array B.

Includes doesn't work, and I don't compare the length, only the values.

I spend many hours looking for an answer but found nothing precisely about this problem.

firstArray = [0,1];
secondArray = [[0,1],[0,2],[0,3],[1,1],[1,2],[1,3]];

How can I can compare firstArray and secondArray, to know if secondArray has the value of firstArray. It is like an equal comparison but only if the value of firstArray is in secondArray.

If it is, then the player can move on the board. The idea is that as long as firstArray value is one of secondArray value, the player can move. If not, no move possible.

Grégory Huyghe
  • 422
  • 1
  • 6
  • 18

3 Answers3

2

You can stringify array items and compare:

var firstArray = [0,1];
var secondArray = [[0,1],[0,2],[0,3],[1,1],[1,2],[1,3]];

var res = secondArray.some(x => JSON.stringify(x) == JSON.stringify(firstArray));
console.log(res);
Mamun
  • 66,969
  • 9
  • 47
  • 59
0

Simply use JSON.stringify with some and sort():

var firstInSecond = secondArray.some(e => JSON.stringify(e.sort()) == JSON.stringify(firstArray.sort()));
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
0

You can use Array.prototype.some() combined with Array.prototype.toString():

const firstArray = [0,1];
const secondArray = [[0,1],[0,2],[0,3],[1,1],[1,2],[1,3]];

const isFound = secondArray.some(a => a.toString() === firstArray.toString());

console.log(isFound);
Yosvel Quintero
  • 18,669
  • 5
  • 37
  • 46