首页 > 解决方案 > 如何排序消除JS中的某些位置

问题描述

我有一个数组如下。

const list = [ {key: 34}, {key: 17}, {key: 28}, {key: 35} ] 

我排序这取决于关键值。

list.sort((a,b)=>{
      return a.key - b.key
    })

我懂了。

const list = [ {key: 17}, {key: 28}, {key: 34}, {key: 35} ] 

但是在某些功能之后,除了第一个位置之外,值会发生变化。例如:

const list = [ {key: 17}, {key: 31}, {key:  2}, {key: 26} ] 

我想再次排序,除了第一个位置。
因此我想得到这个结果:

const list = [ {key: 17}, {key:  2}, {key: 26}, {key: 31} ]

并且重复此过程,除了第一、第二位置直到结束。
我怎样才能为这种情况制作一个排序代码?

标签: javascript

解决方案


我们可以在排序操作中取不考虑的元素,然后对数组进行排序,将元素插入到指定的索引中:

const list = [{key:17},{key:31},{key:2},{key:26}]

function sortWithConstantIndex(arr, index = 0){
  arr = [...arr];
  const val = arr.splice(index, 1).pop();
  arr.sort(({key: aKey}, {key: bKey}) => +aKey - bKey);
  arr.splice(index, 0, val)
  return arr;
}

console.log(sortWithConstantIndex(list));
console.log(sortWithConstantIndex(list, 2));
console.log(sortWithConstantIndex(list, 1));

上面的示例不会改变原始数组。


推荐阅读