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

如何仅将满足连续值条件的JSON对象按规则分组到数组中

问题分析

你当前的代码存在三个核心问题:

  • 未优先判断相邻条目sec和row是否一致,跨区域、跨排的条目也会被错误判断为连续
  • 没有对同区域同排的条目按座位号排序,若原始数据顺序混乱会导致连续判定失效
  • 未过滤掉长度为1的不连续独立条目,不符合你“只保留连续序列”的需求

调整后实现代码

const y = [
  {sec: "100", row: "12", startSeat: 1, endSeat: 2},
  {sec: "125", row: "10", startSeat: 1, endSeat: 2},
  {sec: "125", row: "10", startSeat: 3, endSeat: 4},
  {sec: "125", row: "10", startSeat: 9, endSeat: 10}
];

const result = Object.values(
  // 第一步:按sec+row组合为key分组,不同区域/排的条目完全隔离
  y.reduce((groupMap, item) => {
    const key = `${item.sec}-${item.row}`;
    if (!groupMap[key]) groupMap[key] = [];
    groupMap[key].push(item);
    return groupMap;
  }, {})
).flatMap(group => {
  // 第二步:同组按startSeat升序排序,若原始数据已保证同组顺序可省略该步骤
  const sortedGroup = group.sort((a, b) => a.startSeat - b.startSeat);
  // 第三步:拆分同组内的连续座位块
  const consecutiveBlocks = sortedGroup.reduce((blocks, current, index, arr) => {
    if (index === 0 || current.startSeat !== arr[index-1].endSeat + 1) {
      blocks.push([]);
    }
    blocks[blocks.length - 1].push(current);
    return blocks;
  }, []);
  // 第四步:过滤掉长度为1的独立块,仅保留连续座位条目展开返回
  return consecutiveBlocks.filter(block => block.length >= 2).flat();
});

console.log(result);

输出结果

运行上述代码后得到的结果和你预期完全一致:

[
  {sec: "125", row: "10", startSeat: 1, endSeat: 2},
  {sec: "125", row: "10", startSeat: 3, endSeat: 4}
]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 12:15:00