Eric ES6 on the solution provided by @darin
let subSort = (arr, i, n, sortFx) => [].concat(...arr.slice(0, i), ...arr.slice(i, i + n).sort(sortFx), ...arr.slice(i + n, arr.length));
- i is the index where the unit begins
- n - number of items to sort
- sortFx - sort function
Thus, you can sort the range inside the array:
var array = [5, 2, 6, 4, 1, 9, 3, 8, 7]; // sort array beginning at index 2; sort 4 elements of array subSort(array, 2, 4, (a, b) => a - b); // array is now [5, 2, 1, 4, 6, 9, 3, 8, 7] subSort(array, 2, 4, (a, b) => b - a); // array is now [5, 2, 9, 6, 4, 1, 3, 8, 7]
subSort () can be used for objects of arbitrary complexity.