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
JavaScript
x
22
22
1
let arr = [8, 7, 4, 6, 9, 3, 2, 1];
2
let data = arr.map((val, index, curr) => {
3
if (index == 0) {
4
return curr[index];
5
} else if (index == 1) {
6
return curr[7];
7
} else if (index == 2) {
8
return curr[index];
9
} else if (index == 3) {
10
return curr[5];
11
} else if (index == 4) {
12
return curr[index];
13
} else if (index == 5) {
14
return curr[3];
15
} else if (index == 6) {
16
return curr[index];
17
} else if (index == 7) {
18
return curr[1];
19
}
20
});
21
22
console.log(data);
This is not the correct way to proceed.
Advertisement
Answer
When you consider every odd indexed element to be alternate –
JavaScript
1
11
11
1
let arr = [8, 7, 4, 6, 9, 3, 2, 1];
2
let lastAlternate = arr.length % 2 == 0 ? arr.length : arr.length - 1;
3
let data = arr.map((val, index, curr) => {
4
if (index % 2 == 0) {
5
return curr[index];
6
} else {
7
return curr[lastAlternate - index];
8
}
9
});
10
11
console.log(data);