0

This is a simple code designed to tell me if one array has an array equal to it in an array consisting of arrays. So the following function should be returning true but it returns false.


var TransferR =[0,8,16,24,32,40,48,56]



var rookV =[
[0,8,16,24,32,40,48,56],
[1,9,17,25,33,41,49,57],
[2,10,18,26,34,42,50,58],
[3,11,19,27,35,43,51,59],
[4,12,20,28,36,44,52,60],
[5,13,21,29,37,45,53,61],
[6,14,22,30,38,46,54,62],
[7,15,23,31,39,47,55,63],
]
   

const match = rookV.some(memb=> memb === TransferR)
console.log(match)

  • 2
    [Duplicate](//google.com/search?q=site%3Astackoverflow.com+js+array+comparison+always+false) of [How to compare arrays in JavaScript?](/q/7837456/4642212). – Sebastian Simon Jun 03 '21 at 19:07

2 Answers2

1

You can't compare arrays with ===, which compares the references. Compare array length and then each value.
For example:

const match = rookV.some(memb=> {
  memb.length === TransferR.length && memb.every(el => TransferR.includes(el))
});

This code will first check that there is a match in the length (so it will skip arrays that are uncomparable), and than will check that every element of memb is included in the TransferR array, returning true or false.

ISAE
  • 519
  • 4
  • 12
yanjunk
  • 336
  • 1
  • 5
0

how about stringify it?

var TransferR = [0, 8, 16, 24, 32, 40, 48, 56]



var rookV = [
  [0, 8, 16, 24, 32, 40, 48, 56],
  [1, 9, 17, 25, 33, 41, 49, 57],
  [2, 10, 18, 26, 34, 42, 50, 58],
  [3, 11, 19, 27, 35, 43, 51, 59],
  [4, 12, 20, 28, 36, 44, 52, 60],
  [5, 13, 21, 29, 37, 45, 53, 61],
  [6, 14, 22, 30, 38, 46, 54, 62],
  [7, 15, 23, 31, 39, 47, 55, 63],
]


const match = rookV.some(
  memb => JSON.stringify(memb) === JSON.stringify(TransferR))
console.log(match)
Bryan Dellinger
  • 4,724
  • 7
  • 33
  • 79