Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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.

like image 933
cc young Avatar asked Sep 15 '11 06:09

cc young


1 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]
like image 61
Darin Dimitrov Avatar answered Oct 12 '22 07:10

Darin Dimitrov