-1

we have two same size 2D array.

var firstArray = [
      ['-', '-', '-'],
      ['-', 'X', '-'],
      ['-', '-', 'O']
    ]

var secondArray = [
      ['-', '-', '-'],
      ['-', 'X', '-'],
      ['-', '-', '-']
    ]

after replacing firstArray value with secondArray value, firstArray should be like this

firstArray = [
      ['-', '-', '-'],
      ['-', 'X', '-'],
      ['-', '-', '-']
    ]

I saw this question , but the solution is for flat arrays and I dont want to convert my 2D arrays to flat.

alex
  • 5
  • 2
  • `firstArray = structuredClone(secondArray)`? – trincot Jul 01 '23 at 18:35
  • If the output is equal to the second array, then just set the value to the second array...? I'm, guessing the problem is more complex than this, you've just explained it very badly. – Rory McCrossan Jul 01 '23 at 20:49

2 Answers2

0

One way to do it is to use nested for loops. Try the following code:

for (var i = 0; i < firstArray.length; i++) {
  for (var j = 0; j < firstArray[i].length; j++) {
    firstArray[i][j] = secondArray[i][j];
  }
}

Let me know if this helps.

AlefiyaAbbas
  • 235
  • 11
0

for identical dimensional arrays you can try spread operator like:

firstArray = [...secondArray];

or or arrays of not identical dimensions you can apply loops or you also use function. using function output would create new reference. So that first array would unchanged.

const result = (arr1, arr2) => {
  return arr1.map((el1, i) => {
    return (
      Array.isArray(el1) &&
      el1.map((el2, j) => {
        return (el2 = arr2[i][j]);
      })
    );
  });
};
console.log(result(firstArray, secondArray));