javascript - 如何排序消除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} ]
并且重复此过程,除了第一、第二位置直到结束。
我怎样才能为这种情况制作一个排序代码?
解决方案
我们可以在排序操作中取不考虑的元素,然后对数组进行排序,将元素插入到指定的索引中:
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));
上面的示例不会改变原始数组。
推荐阅读
- python - Enumerate() 函数或类?
- python - 多索引上的前向填充(ffill)
- c# - 如何在第二台计算机上修复不同的十进制设置 C#
- javascript - 尽管使用了 target="_blank",但 React Markdown 链接不会在新选项卡中打开
- linux - 像 PGAdmin 这样的 Oracle Web Tool 用于 Linux 安装?
- http - Golang 大响应 JSON 输入意外结束
- nagios - Nagios 核心摘要宏的计数错误
- eclipse - Jboss 6.1 Eclipse 4.19.0 集成
- python - 如果管理员在 tempbooking django 中将 is_active 更改为“true”,则尝试将所有信息从 Tempbooking 模型解析到 Booking 模型
- javascript - Vue3 - 在路由更改后构建 API url 并获取数据