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

后端 未结 3 928
挽巷
挽巷 2021-02-14 13:25

I have an array and would like to sort all but the last n elements.

For example, if the array is 10 elements long, would like elements 0 through 7 to be sorted while ele

3条回答
  •  渐次进展
    2021-02-14 14:12

    An ES6 riff 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 subsection begins
    • n is the number of elements to sort
    • sortFx is the sorting function

    So it's possible to sort a range within an 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.

提交回复
热议问题