Example of the array:
let arr = [
[1, 1, 1, 1],
[2, 2, 2, 2],
[3, 3, 3, 0],
];
I want to be able to move the '0' left, right, up and down.
for example moving the '0' element up:
[
[1, 1, 1, 1],
[2, 2, 2, 0], //<---
[3, 3, 3, 2],
];
I have been able to move the element LEFT and RIGHT with a function as shown below:
function changePosition(arr, from, to) {
arr.splice(to, 0, arr.splice(from, 1)[0]);
return arr;
}
I'd like to some how move the element UP and DOWN. I would appreciate a hand on this code since I haven't found much on the internet.
CodePudding user response:
you can do something like this
let arr = [
[1, 1, 1, 1],
[2, 2, 2, 2],
[3, 3, 3, 0],
];
const findPos = () => {
const y = arr.findIndex(a => a.includes(0))
return [arr[y].indexOf(0), y]
}
const up = () => {
const [x, y] = findPos()
if (y <= 0) {
return;
}
let temp = arr[y - 1][x]
arr[y - 1][x] = 0
arr[y][x] = temp
}
const down = () => {
const [x, y] = findPos()
if (y >= arr.length - 1) {
return;
}
let temp = arr[y 1][x]
arr[y 1][x] = 0
arr[y][x] = temp
}
const left = () => {
const [x, y] = findPos()
if (x <= 0) {
return;
}
let temp = arr[y][x -1]
arr[y][x - 1] = 0
arr[y][x] = temp
}
const right = () => {
const [x, y] = findPos()
if (x >= arr[y].length - 1) {
return;
}
let temp = arr[y][x 1]
arr[y][x 1] = 0
arr[y][x] = temp
}
console.log(arr, findPos())
up()
console.log(arr, findPos())
left()
console.log(arr, findPos())
down()
console.log(arr, findPos())
CodePudding user response:
You can try to swap the values to whatever index you like.
function swap(yourArray,topOrBottomArray,positionOfYourNum){
//positionOfYourNum is 3 in your case
let temp = yourArray[positionOfYourNum];
yourArray[positionOfYourNum] = topOrBottomArray[positionOfYourNum];
topOrBottomArray[positionOfYourNum] = temp;
}
Then just call
swap(arr[2],arr[1],3); //3 is the index of 0
console.log(arr);
Result = [
[1, 1, 1, 1],
[2, 2, 2, 0],
[3, 3, 3, 2],
];