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

如何进行数据分组?如何编写数组元素序列分组脚本?

实现数组按Id序列分组的脚本

我来帮你搞定这个数组分组的需求,下面给你详细的实现思路和代码示例,不管你要数组的数组还是数组的对象,都有对应的方案~

先明确规则(怕理解错再捋一遍)

咱们的分组逻辑核心就是看相邻元素的Id差:

  • 如果当前元素的Id和前一个元素的Id差≤1(不管是相等还是大1),就归到当前组
  • 如果差≥2,那就得新建一个组放这个元素

方案1:分组为数组的数组(最常用的场景)

这里用数组的reduce方法来实现,它天生适合这种遍历累积结果的操作,代码简洁高效:

function groupBySequence(items) {
  // 先处理空数组的边界情况
  if (!items.length) return [];
  
  return items.reduce((groups, currentItem) => {
    // 拿到当前最后一个分组
    const lastGroup = groups[groups.length - 1];
    
    // 如果是第一个元素,直接创建新分组
    if (!lastGroup) {
      groups.push([currentItem]);
      return groups;
    }
    
    // 取最后一个分组里最后一个元素的Id
    const lastId = lastGroup[lastGroup.length - 1].id;
    
    // 判断是否属于当前序列:差≤1就加进当前组,否则建新组
    if (currentItem.id - lastId <= 1) {
      lastGroup.push(currentItem);
    } else {
      groups.push([currentItem]);
    }
    
    return groups;
  }, []);
}

// 来个测试用例看看效果
const testItems = [
  { id: 1, name: '商品A' },
  { id: 2, name: '商品B' },
  { id: 4, name: '商品C' },
  { id: 5, name: '商品D' },
  { id: 6, name: '商品E' },
  { id: 9, name: '商品F' }
];

console.log(groupBySequence(testItems));

运行结果

输出就是咱们想要的分组数组:

[
  [ { id: 1, name: '商品A' }, { id: 2, name: '商品B' } ],
  [ { id: 4, name: '商品C' }, { id: 5, name: '商品D' }, { id: 6, name: '商品E' } ],
  [ { id: 9, name: '商品F' } ]
]

方案2:分组为数组的对象(用序列起始Id当键)

如果你的场景需要把分组结果变成对象,比如用每组第一个元素的Id作为键,那稍微改改代码就行:

function groupBySequenceAsObject(items) {
  if (!items.length) return {};
  
  return items.reduce((groupObj, currentItem) => {
    // 拿到当前对象里所有的分组键
    const groupKeys = Object.keys(groupObj);
    const lastKey = groupKeys[groupKeys.length - 1];
    
    // 第一个元素直接建分组
    if (!lastKey) {
      groupObj[currentItem.id] = [currentItem];
      return groupObj;
    }
    
    const lastGroup = groupObj[lastKey];
    const lastId = lastGroup[lastGroup.length - 1].id;
    
    // 同样的规则判断分组
    if (currentItem.id - lastId <= 1) {
      lastGroup.push(currentItem);
    } else {
      groupObj[currentItem.id] = [currentItem];
    }
    
    return groupObj;
  }, {});
}

// 测试一下
console.log(groupBySequenceAsObject(testItems));

运行结果

这次输出是对象形式:

{
  "1": [ { id: 1, name: '商品A' }, { id: 2, name: '商品B' } ],
  "4": [ { id: 4, name: '商品C' }, { id: 5, name: '商品D' }, { id: 6, name: '商品E' } ],
  "9": [ { id: 9, name: '商品F' } ]
}

几个要注意的点

  1. 输入数组必须是按Id升序排列的!如果你的数组是乱序的,一定要先排序,比如在分组前加一行:items.sort((a, b) => a.id - b.id)
  2. 代码里默认元素的Id字段是id,如果你的字段名是userId或者其他,直接替换成对应的字段就行
  3. 边界情况都处理了,比如空数组、只有一个元素的数组,都能正常返回结果

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:12:32