
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
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 ]
- Related Articles
- Write a program to reverse an array in JavaScript?
- How to reverse the order of a JavaScript array?
- How to use map() on an array in reverse order with JavaScript?
- Array reverse() in JavaScript
- JavaScript Array reverse()
- How to extract the hostname portion of a URL in JavaScript?
- How to reverse an Array using STL in C++?
- How to get a decimal portion of a number with JavaScript?
- Reverse sum array JavaScript
- How to reverse the elements of an array using stack in java?
- Reverse an array in C++
- Reverse index value sum of array in JavaScript
- Reverse digits of an integer in JavaScript without using array or string methods
- Write a Golang program to reverse an array
- Java program to reverse an array

Advertisements