Partially reversing an array - JavaScript


Suppose, we have an array of literals like this −

const arr = [3, 5, 5, 2, 23, 4, 7, 8, 8, 9];

We are required to write a JavaScript function that takes in such an array and a number, say n (n must be less than or equal to the length of array). And the function should reverse the first n elements of the array within.

For example −

If for this array, the number is 4 −

const arr = [3, 5, 5, 2, 23, 4, 7, 8, 8, 9];

Then the output should be −

const output = [2, 5, 5, 3, 23, 4, 7, 8, 8, 9];

Example

Let us write the code for this function −

const arr = [3, 5, 5, 2, 23, 4, 7, 8, 8, 9];
const partialReverse = (arr = [], num = 0) => {
   const partialArr = arr.slice(0, num);
   partialArr.reverse();
   arr.splice(0, num, ...partialArr);
};
partialReverse(arr, 5);
console.log(arr);

Output

Following is the output in the console −

[
   23, 2, 5, 5, 3,
   4, 7, 8, 8, 9
]

Updated on: 16-Sep-2020

303 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements