Search code examples
javascriptarraysdata-structures

Reverse the second half of array elements in js


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])
}


Solution

  • 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, then push() them all back into a.

    let a = [5, 17, 11, 10, 12, 6];
    let b = a.splice(a.length / 2).reverse();
    a.push(...b);
    console.log(a); // [5, 17, 11, 6, 12, 10]

    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 using Math.floor() on the calculation of a.length / 2 - the acceptability of this will depend on your requirements and constraints.`