How to sort the part of an array in JavaScript

1 Answer

0 votes
let arr = [15, 6, 19, 8, 3, 7, 9, 1, 4];

// Extract the slice from index 2 to 6 (inclusive)
let slice = arr.slice(2, 7);

// Sort the slice in ascending order
slice.sort((a, b) => a - b);

// Replace the original slice with the sorted one
arr.splice(2, 5, ...slice);

// Print the updated array
console.log(arr);



/*
run:

[15, 6, 3, 7, 8, 9, 19, 1, 4]

*/

 



answered Aug 12, 2025 by avibootz
...