最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin26浏览0评论

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.

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.

Share Improve this question asked Sep 15, 2011 at 6:12 cc youngcc young 20.2k32 gold badges94 silver badges150 bronze badges
Add a comment  | 

6 Answers 6

Reset to default 19
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]

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

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.

let arr = [2, 1, 5, 4, 3];
arr = [...arr.slice(0, 2), ...arr.slice(2).sort((a, b) => a - b)];

After sorting a sub-array the original array will be [2, 1, 3, 4, 5]

splice can be used to remove part of array and insert sorted part of the array :

const a = [9,8,7,6,5,4,3,2,1];

a.splice(3, 3, ...a.slice(3, 6).sort());

console.log( JSON.stringify( a ) );         // [9,8,7,4,5,6,3,2,1]

Following function sorts part of array in-place, by first copying part to be sorted into temporary array and then copying sorted elements back to correct position. This solution creates only 1 additional array (some other answers do more) and does not overflow stack if there are a lot of elements.

function arraySortPart (array, from, to, compare) {
  const toSort = array.slice(from, to);
  toSort.sort(compare);
  for (let i = from; i < to; ++i) {
    array[i] = toSort[i - from];
  }
  return array;
}

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论
ok 不同模板 switch ($forum['model']) { /*case '0': include _include(APP_PATH . 'view/htm/read.htm'); break;*/ default: include _include(theme_load('read', $fid)); break; } } break; case '10': // 主题外链 / thread external link http_location(htmlspecialchars_decode(trim($thread['description']))); break; case '11': // 单页 / single page $attachlist = array(); $imagelist = array(); $thread['filelist'] = array(); $threadlist = NULL; $thread['files'] > 0 and list($attachlist, $imagelist, $thread['filelist']) = well_attach_find_by_tid($tid); $data = data_read_cache($tid); empty($data) and message(-1, lang('data_malformation')); $tidlist = $forum['threads'] ? page_find_by_fid($fid, $page, $pagesize) : NULL; if ($tidlist) { $tidarr = arrlist_values($tidlist, 'tid'); $threadlist = well_thread_find($tidarr, $pagesize); // 按之前tidlist排序 $threadlist = array2_sort_key($threadlist, $tidlist, 'tid'); } $allowpost = forum_access_user($fid, $gid, 'allowpost'); $allowupdate = forum_access_mod($fid, $gid, 'allowupdate'); $allowdelete = forum_access_mod($fid, $gid, 'allowdelete'); $access = array('allowpost' => $allowpost, 'allowupdate' => $allowupdate, 'allowdelete' => $allowdelete); $header['title'] = $thread['subject']; $header['mobile_link'] = $thread['url']; $header['keywords'] = $thread['keyword'] ? $thread['keyword'] : $thread['subject']; $header['description'] = $thread['description'] ? $thread['description'] : $thread['brief']; $_SESSION['fid'] = $fid; if ($ajax) { empty($conf['api_on']) and message(0, lang('closed')); $apilist['header'] = $header; $apilist['extra'] = $extra; $apilist['access'] = $access; $apilist['thread'] = well_thread_safe_info($thread); $apilist['thread_data'] = $data; $apilist['forum'] = $forum; $apilist['imagelist'] = $imagelist; $apilist['filelist'] = $thread['filelist']; $apilist['threadlist'] = $threadlist; message(0, $apilist); } else { include _include(theme_load('single_page', $fid)); } break; default: message(-1, lang('data_malformation')); break; } ?>