In javascript, how do you sort a subset of an array?

I have an array and would like to sort everything except the last n elements.

For example, if the array has a length of 10 elements, you need to sort the elements from 0 to 7, and elements 8-9 will remain in place.

+4
source share
3 answers
var array = [5, 2, 6, 4, 1, 9, 3, 8, 7]; array = array.slice(0, 7).sort().concat(array.slice(7, 10)); // array is now [1, 2, 3, 4, 5, 6, 9, 8, 7] 
+11
source

If you need to sort the array in place (i.e. without creating a new, sorted array), which does the sort() method, you can do the following:

 var array = [5, 2, 6, 4, 0, 1, 9, 3, 8, 7]; var unsorted = array.slice(7); array.length = 7; array.sort().push.apply(array, unsorted); 

In general, here is a function for sorting part of an array in place. Like the sort() method, it also returns an array reference.

 function partialSort(arr, start, end) { var preSorted = arr.slice(0, start), postSorted = arr.slice(end); var sorted = arr.slice(start, end).sort(); arr.length = 0; arr.push.apply(arr, preSorted.concat(sorted).concat(postSorted)); return arr; } 

Example:

 var array = [5, 2, 6, 4, 0, 1, 9, 3, 8, 7]; partialSort(array, 0, 7); 
+3
source

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.

+2
source

All Articles