I need to make a function to change the positions of an array, temporarily. I have the following array:
var grilla = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
I want to pass the positions by parameter:
function intercambiarPosicionesGrilla(filaPos1, columnaPos1, filaPos2, columnaPos2) {
}
Try to do this but it doesn't work:
function intercambiarPosicionesGrilla(filaPos1, columnaPos1, filaPos2, columnaPos2) {
var x = (grilla[filaPos1][columnaPos1] = grilla[filaPos2][columnaPos2]);
}
I'm new to JS and I'm pretty lost. I can't think of any other way to do it. Can you help me?
I hope to do this:
intercambiarPosiciones(1, 1, 1, 2);
RESULT:
grilla = [[1, 2, 3],
[4, 6, 5],
[7, 8, 9]];
Do you know the propagation operators ?, well here is a simple example of how to use it basically I say
[valorA,valorB] = [valorB,valorA]
, avoiding declaring temporary variables the example below! , to copy the array we use lodash , because all native JavaScript functions shallowly copy arrays/objectsAnother way to solve it would be the following
Where the array and parameters are passed to a function that makes the changes and returns a new transformed object.