Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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'];
Method 1: Using splice() with In-Place Modification
This approach extracts the portion to be sorted, sorts it, and places it back into the original array.
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);
[ 'b', 'z', 'a' ]
Method 2: Using slice() Without Modifying Original Array
This approach creates a new array with the sorted portion, leaving the original array unchanged.
const arr = ['z', 'b', 'a'];
const sortBetween = (arr = [], start, end) => {
const before = arr.slice(0, start);
const part = arr.slice(start, end + 1).sort();
const after = arr.slice(end + 1);
return [...before, ...part, ...after];
}
const result = sortBetween(arr, 0, 1);
console.log("Original:", arr);
console.log("Sorted:", result);
Original: [ 'z', 'b', 'a' ] Sorted: [ 'b', 'z', 'a' ]
Example with Numbers
The same function works with numeric arrays:
const numbers = [8, 3, 7, 1, 9];
const sortBetween = (arr = [], start, end) => {
const part = arr.splice(start, end - start + 1);
part.sort((a, b) => a - b); // Numeric sort
arr.splice(start, 0, ...part);
}
sortBetween(numbers, 1, 3);
console.log(numbers);
[ 8, 1, 3, 7, 9 ]
Comparison
| Method | Modifies Original | Memory Usage | Best For |
|---|---|---|---|
| splice() | Yes | Lower | In-place sorting |
| slice() | No | Higher | Immutable operations |
Key Points
- Use
splice()for in-place modifications - Use
slice()to preserve the original array - For numbers, use
sort((a, b) => a - b)for proper numeric sorting - The end index is inclusive in our implementation
Conclusion
Partial array sorting can be achieved using either splice() for in-place modification or slice() for immutable operations. Choose based on whether you need to preserve the original array.
