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

如何按指定类型优先级对JavaScript对象数组进行最优排序

JavaScript自定义分类排序实现方案

最优实现思路

该场景下不需要使用复杂度为O(nlogn)的Array.sort()方法,仅需一次遍历分类、倒序拼接即可完成需求,整体时间复杂度为O(n),是性能最优的实现逻辑:

  • 单次遍历原数组,将元素按type值分别存入三个独立分组数组
  • 对三个分组数组统一做倒序处理,符合要求的「从原数组末尾倒序选取」规则
  • 按优先级顺序Fruit → Animal → Plant拼接三个倒序后的分组数组,得到最终结果

可直接运行的代码实现

var array = [{value:"13",type:"Fruit"},{value:"61",type:"Animal"},
             {value:"19",type:"Fruit"},{value:"71",type:"Animal"},
             {value:"12",type:"Fruit"},{value:"15",type:"Fruit"}, 
             {value:"11",type:"Plant"},{value:"10",type:"Fruit"}, 
             {value:"16",type:"Plant"}];

// 初始化分组容器
const typeGroups = {
  Fruit: [],
  Animal: [],
  Plant: []
};

// 一次遍历完成分类
for (const item of array) {
  typeGroups[item.type].push(item);
}

// 倒序后按优先级拼接得到结果
const sortedResult = [
  ...typeGroups.Fruit.reverse(),
  ...typeGroups.Animal.reverse(),
  ...typeGroups.Plant.reverse()
];

注:你给出的预期输出里出现的Fruits为笔误,代码运行结果除修正该笔误外,其余顺序完全匹配预期。

内容的提问来源于stack exchange,提问作者Adarsh Jaiswal

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 13:54:02