
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Sorting Only a Part of an Array in 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' ]
Advertisements