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

后端 未结 3 986
挽巷
挽巷 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:20

    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]
    

提交回复
热议问题