skip to Main Content

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


  1. 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.`

    Login or Signup to reply.
  2. 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:

    const array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
    const half = Math.ceil(array.length / 2);
    
    let firstHalf = array.splice(0, half);
    let secondHalf = array.splice(-half);
    let secondHalfReversed = [];
    
    for (let i = secondHalf.length - 1; i >= 0; i--) {
      secondHalfReversed.push(secondHalf[i]);
    }
    
    const finalArray = [...firstHalf, ...secondHalfReversed];
    
    console.log(finalArray);
    Login or Signup to reply.
  3. 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.

    let a = [5, 17, 11, 10, 12, 6];
    let h = a.length / 2;
    let r = [
      ...a.slice(0, h),
      ...a.slice(h).reverse()
    ];
    
    console.log(r); // [5, 17, 11, 6, 12, 10]
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search