Sorting only a part of an array JavaScript


We are required to write a JavaScript function that takes in an array of strings as the first argument and two numbers as second and third argument respectively.

The purpose of our function is to sort the array. But we have to sort only that part of the array that falls between the start and end indices specified by second and third argument. Keeping all the other elements unchanged.

For example −

const arr = ['z', 'b', 'a'];
sortBetween(arr, 0, 1);

This function should sort the elements at 0 and 1 index only. And the array should become −

const output = ['b', 'z', 'a'];

Example

const arr = ['z', 'b', 'a'];
const sortBetween = (arr = [], start, end) => {
   const part = arr.splice(start, end - start + 1);
   part.sort();
   arr.splice(start, 0, ...part);
}
sortBetween(arr, 0, 1);
console.log(arr);

Output

And the output in the console will be −

[ 'b', 'z', 'a' ]

Updated on: 23-Nov-2020

566 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements