skip to Main Content

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.

3

Answers


  1. 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.

    Login or Signup to reply.
  2. To replace the values of one 2D array with another 2D array without converting them to flat arrays, you can use nested loops to iterate over each element and assign the corresponding value from the second array to the first array.

    Here is my tested code.

    var firstArray = [
      ['-', '-', '-'],
      ['-', 'X', '-'],
      ['-', '-', 'O']
    ];
    
    var secondArray = [
      ['-', '-', '-'],
      ['-', 'X', '-'],
      ['-', '-', '-']
    ];
    
    // Iterate over each row and column
    for (var i = 0; i < firstArray.length; i++) {
      for (var j = 0; j < firstArray[i].length; j++) {
        // Assign the value from secondArray to firstArray
        firstArray[i][j] = secondArray[i][j];
      }
    }
    
    console.log(firstArray);
    
    // Output
    [
      ['-', '-', '-'],
      ['-', 'X', '-'],
      ['-', '-', '-']
    ]
    
    Login or Signup to reply.
  3. 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));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search