camel812
camel812

Reputation: 13

Swap arbitrary 3D Array Values

I have the following array:

array = [[[1,2],[4,5]],[[6,7],[8,9]]];

I would like to have the following result:

easyArray = [[[2,1],[5,4]],[[7,6],[9,8]]];

I tried

function swapCoordinates(array){
var a=0;
var b=0;
    for (j=0;j<array[0].length;j++){
        for (k=0;k<array[0][0].length;k++){
            var swap = array[a][b][0];
            array[a][b][0] = array[a][b][1];
            array[a][b][1] = swap
            console.log(a);
            a++;
            console.log(b);

        }
        console.log(a);
        console.log(b);
        b++

    }

return array;
}

The problem with it is, that I don't know how to increment b properly to get also e.g. array[1,0,0] ...

What am I doing wrong?

Upvotes: 0

Views: 29

Answers (2)

Redu
Redu

Reputation: 26191

You may do as follows;

var array  = [[[1,2],[4,5]],[[6,7],[8,9]]],
    swap3D = ([e0,e1,...es]) => e0 ? Array.isArray(e0) ? [swap3D(e0)].concat(swap3D([e1,...es]))
                                                       : [e1,e0]
                                   : [],
    result = JSON.stringify(swap3D(array));
console.log(result);

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386756

You could use a recursive approach by checking if the item is an array with another array inside.

Then either map the arrays or return swapped items.

var array = [[[1, 2], [4, 5]], [[6, 7], [8, 9]]],
    swapped = array.map(function swap(a) {
        return Array.isArray(a) && Array.isArray(a[0])
            ? a.map(swap)
            : a.slice().reverse();
    });
    
console.log(swapped);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Upvotes: 1

Related Questions