You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用npm库array-sort实现对象数组多动态键自定义升降序排序

使用array-sort实现指定字段降序排序的方法

array-sort本身已原生支持自定义字段排序方向,有两种实现方式可选:

方法1:字段名加前缀(最简便)

在需要降序排序的字段名前添加-前缀即可,升序字段不用加任何前缀,排序优先级按传入字段的顺序从高到低:

const arraySort = require('array-sort');

const input = [
  {id:'1',name:'John',city:'Denver',State:'CO'},
  {id:'2',name:'Smith',city:'San Fransisco',State:'CA'},
  {id:'3',name:'Adam',city:'Concord',State:'CA'},
  {id:'1',name:'John',city:'Concord',State:'CA'}
];

// 按State升序、city升序、id降序排序
const sortedResult = arraySort(input, ['State', 'city', '-id']);
console.log(sortedResult);

输出结果和你给出的预期完全一致。

方法2:通过配置项指定降序字段

如果你的字段名本身就以-开头,不适合用前缀方式,可以在第三个参数的配置项中通过desc属性指定需要降序的字段列表:

const sortedResult = arraySort(input, ['State', 'city', 'id'], {
  desc: ['id']
});

内容的提问来源于stack exchange,提问作者Sadiq Sikkandhar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.14 15:36:07