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

JavaScript中按特定规则排序JSON数据的问题求助

问题解决:按指定规则排序JSON数组

你的排序逻辑需要分两种情况处理:当两个元素的Score都是30时,按Time升序排列;其他情况按Score降序排列。当前代码只实现了Score降序,未处理Score为30时的Time排序逻辑,且原数据中Score和Time都是字符串类型,排序时需要先转为数字避免字符串比较的问题。

修正后的代码

const text = [{
  "Name": "Tomas",
  "Score": "30",
  "Time": "105"
}, {
  "Name": "Ank",
  "Score": "26",
  "Time": "110"
}, {
  "Name": "Alex",
  "Score": "28",
  "Time": "120"
}, {
  "Name": "Mac",
  "Score": "30",
  "Time": "104"
}]

text.sort(function(a, b) {
  // 将字符串转为数字,避免字符串排序的错误
  const scoreA = Number(a.Score);
  const scoreB = Number(b.Score);
  const timeA = Number(a.Time);
  const timeB = Number(b.Time);

  // 情况1:两个元素的Score都是30,按Time升序
  if (scoreA === 30 && scoreB === 30) {
    return timeA - timeB;
  }
  // 情况2:其他情况,按Score降序
  return scoreB - scoreA;
});

displayCars();

function displayCars() {
  document.getElementById("demo").innerHTML =
    text[0].Time + " - " + text[0].Name + "<br>" +
    text[1].Time + " - " + text[1].Name + "<br>" +
    text[2].Time + " - " + text[2].Name + "<br>" +
    text[3].Time + " - " + text[3].Name;
}
<p id="demo"></p>

逻辑说明

  1. 类型转换:将Score和Time字符串转为数字,确保排序时是数值比较而非字符串字典序比较(比如字符串"105"和"104"直接比较会出现逻辑错误)。
  2. 双条件排序:
    • 当两个元素的Score都为30时,返回timeA - timeB,实现Time升序(返回负数则a排在b前面)。
    • 其他情况返回scoreB - scoreA,实现Score降序(分数高的元素排在前面)。

这样排序后就能得到你期望的结果:Score为30的元素按Time从小到大排列,其余元素按Score从高到低排列。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 07:32:02