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

后端 未结 3 994
挽巷
挽巷 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条回答
  •  萌比男神i
    2021-02-14 14:23

    If you need to sort the array in place (i.e. without creating a new, sorted array), which is what the sort() method does, you could 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);
    

    More generally, here's a function to sort a portion of an array in place. Like the sort() method, it also returns a reference to the array.

    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);
    

提交回复
热议问题