Benjamin RD
Benjamin RD

Reputation: 12034

Typescript change position of arrays elements (odd with even)

This is the extract of my scenario. I have an array with coordinates, let me do the example with integer numbers.

const myArray = [1,2,3,4,5,6,7,8];

And the output array I expect is:

finalArray = [2,1,4,3,6,5,8,7];

I just want to change the even and odds position, but not to invert the array.

Can someone explain to me how to do it?

I'm trying to do it with a map, but still no luck

Upvotes: 0

Views: 351

Answers (2)

Jared Smith
Jared Smith

Reputation: 21965

Assuming your array of [1,2,3,4,5,6,7,8] either of these will work but they have some caveats.

If your array is guaranteed to be even length:

array.map((x, i, arr) => i % 2 ? arr[i - 1] : arr[i + 1]) 

If your array is not guaranteed to be even but contains no falsey values (e.g. zero):

array.map((x, i, arr) => ((i % 2 ? arr[i - 1] : arr[i + 1]) || x))

If your array isn't guaranteed to be even, and may contain falsey values you'll have to use the second and replace the simple logical or with a check for undefined.

Upvotes: 2

Aplet123
Aplet123

Reputation: 35530

If your array is guaranteed to be of even length, then you can use a loop and push into a new array:

const finalArray = [];
for (let i = 0; i < myArray.length; i += 2) {
    finalArray.push(myArray[i + 1]);
    finalArray.push(myArray[i]);
}

Or, you can do it in place by swapping:

for (let i = 0; i < myArray.length; i += 2) {
    const temp = myArray[i];
    myArray[i] = myArray[i + 1];
    myArray[i + 1] = myArray[i];
}

Or, you can even do it with a map by xorring the index by 1 (this has the effect of decreasing an odd number by 1 and increasing an even number by 1):

const finalArray = myArray.map((_, i) => myArray[i ^ 1]);

Upvotes: 1

Related Questions