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

如何修复数组转换函数,实现按key分组并按类型指定索引排序?

解决方案

核心思路

先按key完成分组,再对每个分组内的元素做顺序调整:将practice类型的对象优先放在偶数索引位(0、2、4...),theory类型放在奇数索引位(1、3、5...),如果某一类数量更多,剩余元素直接追加到组的末尾。

修改后的代码

function transformArray(arr) {
  // 1. 按key分组
  const grouped = arr.reduce((acc, item) => {
    const key = item.key;
    acc[key] = acc[key] || [];
    acc[key].push(item);
    return acc;
  }, {});

  // 2. 调整每个分组的元素顺序
  Object.keys(grouped).forEach(key => {
    const group = grouped[key];
    const practiceItems = group.filter(i => i.type === 'practice');
    const theoryItems = group.filter(i => i.type === 'theory');
    const orderedGroup = [];

    let pIdx = 0;
    let tIdx = 0;

    // 交替添加practice和theory,直到其中一类被取完
    while (pIdx < practiceItems.length || tIdx < theoryItems.length) {
      if (pIdx < practiceItems.length) {
        orderedGroup.push(practiceItems[pIdx]);
        pIdx++;
      }
      if (tIdx < theoryItems.length) {
        orderedGroup.push(theoryItems[tIdx]);
        tIdx++;
      }
    }

    grouped[key] = orderedGroup;
  });

  // 若需要返回展开后的一维数组则用flat(),若需要保留分组结构则直接返回grouped
  return Object.values(grouped).flat();
}

输入输出示例

输入

const inputArr = [
  { key: 'math', type: 'theory' },
  { key: 'math', type: 'practice' },
  { key: 'english', type: 'practice' },
  { key: 'math', type: 'practice' },
  { key: 'english', type: 'theory' },
  { key: 'english', type: 'theory' }
];

预期输出

[
  { key: 'math', type: 'practice' },
  { key: 'math', type: 'theory' },
  { key: 'math', type: 'practice' },
  { key: 'english', type: 'practice' },
  { key: 'english', type: 'theory' },
  { key: 'english', type: 'theory' }
]

代码说明

  • 分组环节用Array.reduce()高效归类相同key的元素
  • 顺序调整时,先分离两类元素,再通过循环交替推入结果数组,确保practice优先占据偶数索引位
  • 末尾的返回值可根据需求选择:保留分组结构返回grouped,或者展开为一维数组返回Object.values(grouped).flat()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 08:12:50