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

如何按指定名称顺序对JS对象数组进行过滤及自定义排序?

问题原因

  1. 字符串匹配错误:原数据里Smart 6对应的title是Smart 6(两个连续空格),但你定义的排序基准数组tariffOrder里写的是Smart 6(仅一个空格)。indexOf是严格匹配字符串的,匹配失败就会返回-1,两个元素的索引都为-1时,你的三元判断逻辑无法正确区分优先级,就会出现排序错乱。
  2. 排序比较函数写法不严谨:直接返回两个索引的差值是更符合JS sort函数规范的写法,能避免边界场景下的排序错误。

解决方法

首先统一字符串的空格格式,同时优化排序写法,修正后的可运行代码如下:

const data = [
   {
      "title":"Smart S",
      "tariff_id":"1301"
   },
   {
      "title":"Smart M",
      "tariff_id":"1306"
   },
   {
      "title":"Smart L",
      "tariff_id":"1303"
   },
   {
      "title":"Start",
      "tariff_id":"1304"
   },
   {
      "title":"Smart  6",
      "tariff_id":"1305"
   },
   {
      "title":"Ausland",
      "tariff_id":"888888",
   },
   {
      "title":"Länderzone",
      "tariff_id":"999999",
   }
];

// 过滤无效数据
const newTariffs = (data || []).filter((tariff) =>
          tariff?.tariff_id != 888888 && tariff?.tariff_id != 999999
);

// 修正排序基准数组的空格,和原数据匹配
const tariffOrder = ["Start", "Smart S", "Smart M", "Smart L", "Smart  6"]; 

// 优化排序逻辑:直接返回索引差值,效率更高逻辑更稳
const sortedTariffs = (newTariffs || []).sort((a, b) =>
    tariffOrder.indexOf(a.title) - tariffOrder.indexOf(b.title)
);


console.log("sortedTariffs ", sortedTariffs);

运行后输出就和你预期的结果完全一致。如果担心后续还有空格不一致的问题,也可以在匹配的时候先统一去除多余空格:

// 排序时先处理字符串的空格再匹配
const sortedTariffs = (newTariffs || []).sort((a, b) => {
    const aTitle = a.title.replace(/\s+/g, ' ').trim()
    const bTitle = b.title.replace(/\s+/g, ' ').trim()
    const order = ["Start", "Smart S", "Smart M", "Smart L", "Smart 6"]
    return order.indexOf(aTitle) - order.indexOf(bTitle)
});

内容的提问来源于stack exchange,提问作者Hello World

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 15:15:04