Skip to content
Advertisement

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

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 elements 8-9 are left in place.

Advertisement

Answer

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]
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement