Skip to content
Advertisement

Swapping array with alternative numbers

In an array take alternate numbers and swap them. Put it again in the place of array again e.g., arr = [8,7,4,6,9,3,2,1] newarr= [8,1,4,3,9,6,2,7]

The Code which I tried is below one

let arr = [8, 7, 4, 6, 9, 3, 2, 1];
let data = arr.map((val, index, curr) => {
  if (index == 0) {
    return curr[index];
  } else if (index == 1) {
    return curr[7];
  } else if (index == 2) {
    return curr[index];
  } else if (index == 3) {
    return curr[5];
  } else if (index == 4) {
    return curr[index];
  } else if (index == 5) {
    return curr[3];
  } else if (index == 6) {
    return curr[index];
  } else if (index == 7) {
    return curr[1];
  }
});

console.log(data);

This is not the correct way to proceed.

Advertisement

Answer

When you consider every odd indexed element to be alternate –

let arr = [8, 7, 4, 6, 9, 3, 2, 1];
let lastAlternate = arr.length % 2 == 0 ? arr.length : arr.length - 1;
let data = arr.map((val, index, curr) => {
  if (index % 2 == 0) {
    return curr[index];
  } else {
    return curr[lastAlternate - index];
  }
});

console.log(data);
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement