0

My intention is to create PuzzleGame, example http://migo.sixbit.org/puzzles/fifteen/

Main priority is to move Cells from one with value, to another one undefined.

Here is my function:

  moveCell(row, col) {
    this.puzzleTable = [];
    let actRow = 0,
      actCol = 0;

    for (let r = -1; r <= 1; r++) {
      actRow = row + r;
      if (actRow >= 0 && actRow < this.rowCount) {

        moveCells(this.puzzleTable[actRow][col], row, actRow);
      }
    }
    for (let c = -1; c <= 1; c++) {
      actCol = col + c;
      if (actCol >= 0 && actCol < this.colCount) {

        moveCells(this.puzzleTable[row][actCol], col, actCol);

      }
    }
  }

For example:

Arr[0][0] to Arr[1][1]

I do not want to change their value, I want them swap

What is the best practice ?

Krupal Panchal
  • 1,553
  • 2
  • 13
  • 26
  • Possible duplicate of [How to swap two elements inside of a 2D Array in JavaScript? (Confused about what I’m seeing from console.log in Chrome)](https://stackoverflow.com/questions/54697152/how-to-swap-two-elements-inside-of-a-2d-array-in-javascript-confused-about-wha) – Calvin Nunes Nov 28 '19 at 16:09

2 Answers2

0

Well you could simply store the values of both cells in two temporary variables and assign them to each other accordingly.

For example:

var tempA=Arr[0][0];
var tempB=Arr[1][1];
Arr[0][0]=tempB;
Arr[1][1]=tempA;
obscure
  • 11,916
  • 2
  • 17
  • 36
0

This swap looks a lot easier more on How to swap two elements inside of a 2D Array in JavaScript? (Confused about what I’m seeing from console.log in Chrome)

var points = [[1, 2], [10, 20], [100, 200]];
console.log(points.toString());
[points[1], points[2]] = [points[2], points[1]];
var points = [[1, 2], [10, 20], [100, 200]];
console.log(points.toString());
[points[1], points[2]] = [points[2], points[1]];
console.log(points.toString());
Renaldo Balaj
  • 2,390
  • 11
  • 23