Here, I have written a program that traverses and reverses the last part of the array elements, like if the array is [5, 17, 11, 10, 12, 6]
, and I want output like [5, 17, 11, 6, 12, 10]
, so I have written a program, but the output is not coming out as expected. Can you please check and modify that so that I will get the desired result?
let a = [5, 17, 11, 10, 12, 6];
let n = a.length;
for (let i = 0, j = (n / 2) - 1; i < n / 4; i++, j--) {
let temp = a[n / 2 + i];
a[n / 2 + i] = a[j];
a[j] = temp;
}
for (i = 0; i < n; i++) {
console.log(a[i])
}
3
Answers
No need for all the extra rigmarole you’ve got to loop over
Array
elements – instead,splice()
the original array halfway,reverse()
the spliced values, thenpush()
them all back intoa
.As I mentioned in my comment – be forewarned that this will not function the way you seemingly want it to if
a.length % 2 != 0
, so you may consider usingMath.floor()
on the calculation ofa.length / 2
– the acceptability of this will depend on your requirements and constraints.`You can divide the array in two parts and reverse the secondHalf using the
reverse
js method.If you don’t want to use the
reverse
you can follow this approach:This is similar to @esqew but a version that doesn’t mutate the original array..
And his comments on none even array lengths still applies here.