How to reverse a portion of an array in JavaScript?


We are required to write a JavaScript function that takes in an array, a start index and an end index. The function should reverse the portion of the array between the start index and end index.

For example −

If the array is −

const arr = [2, 6, 5, 8, 3, 5, 2, 6, 7];

And the start index and end index are 3, 7 respectively, then the array should be reversed to −

const output = [2, 6, 5, 2, 5, 3, 8, 6, 7];

Example

Following is the code −

const arr = [2, 6, 5, 8, 3, 5, 2, 6, 7];
const start = 3, end = 7;
const reverse = arr => {
   const { length: l } = arr;
   for(let i = 0; i < Math.floor(l/2); i++){
      const temp = arr[i];
      arr[i] = arr[l-i-1];
      arr[l-i-1] = temp;
   };
   return arr;
};
const reverseBetween = (arr, start, end) => {
   const num = Math.min(end - start, arr.length - start);
   arr.splice(start, 0, ...reverse(arr.splice(start, num)));
}
reverseBetween(arr, start, end);
console.log(arr);

Output

This will produce the following output in console −

[
   2, 6, 5, 2, 5,
   3, 8, 6, 7
]

Updated on: 30-Sep-2020

207 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements