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

JavaScript已排序对象数组的同分值元素分组及文本输出问题

按score分组并生成选择文本的正确实现

需求说明

现有一个已按score排序的对象数组(示例为分数从高到低排列),结构如下:

var sorted = [
    {
        section:"Red",
        score:12
    },
    {
        section:"Green",
        score:12
    },
    {
        section:"Blue",
        score:9
    },
    {
        section:"Yellow",
        score:8
    },
    {
        section:"Grey",
        score:6
    },
    {
        section:"Black",
        score:6
    }
]

需要将相同score的元素分组,生成类似您的第一选择是Red和Green,第二选择是Blue,第三选择是Yellow,第四选择是Grey和Black的文本输出。

原代码问题分析

原代码存在以下核心问题:

  • 循环从i=1开始,直接遗漏数组第一个元素
  • 分组逻辑错误:仅当当前元素与前一个元素score不同时才新建分组,完全未处理第一个分组的初始化与元素添加
  • 分组内容冗余包含score,不符合最终只展示section名称的需求

正确实现方法

步骤1:按score分组

遍历数组,将同分数的section归类到同一组:

const groupByScore = (arr) => {
  if (!arr.length) return [];
  const groups = [];
  let currentGroup = [arr[0].section];
  
  for (let i = 1; i < arr.length; i++) {
    if (arr[i].score === arr[i-1].score) {
      currentGroup.push(arr[i].section);
    } else {
      groups.push(currentGroup);
      currentGroup = [arr[i].section];
    }
  }
  groups.push(currentGroup);
  return groups;
};

步骤2:生成目标文本

基于分组结果,构建带序号的选择文本:

const generateChoiceText = (groups) => {
  if (!groups.length) return "暂无选择";
  
  const choiceTexts = groups.map((group, index) => {
    const order = ["第一", "第二", "第三", "第四", "第五"][index] || `第${index+1}`;
    let sectionStr = group.length === 1 
      ? group[0] 
      : `${group.slice(0, -1).join("、")}和${group[group.length-1]}`;
    return `${order}选择是${sectionStr}`;
  });
  
  return `您的${choiceTexts.join(",")}。`;
};

完整调用示例

var sorted = [
    { section:"Red", score:12 },
    { section:"Green", score:12 },
    { section:"Blue", score:9 },
    { section:"Yellow", score:8 },
    { section:"Grey", score:6 },
    { section:"Black", score:6 }
];

const groups = groupByScore(sorted);
const resultText = generateChoiceText(groups);
console.log(resultText);
// 输出:您的第一选择是Red和Green,第二选择是Blue,第三选择是Yellow,第四选择是Grey和Black。

补充说明

  • 如果原始数组是升序(分数从小到大),需优先展示高分项的话,可先反转数组:const sortedDesc = [...sorted].reverse();再传入分组函数
  • 序号超过5个时,会自动使用第N格式,无需额外配置

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 08:15:28