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

如何反转数组展平操作?将一维数组转为每组两元素的二维数组

如何将一维数组按固定长度分组为二维数组?

嘿,我懂你想要做的事——把之前用reduce展平得到的一维数组,再还原成每组2个元素的二维数组对吧?刚好有几种实用又易懂的方法,我来给你一步步说明:

方法1:用reduce实现(和你之前的展平逻辑呼应)

既然你之前用reduce做了数组展平,那用它来做反转操作也很合适,逻辑上能对应起来:

const originalArray = [0, 1, 2, 3, 4, 5];
const groupedArray = originalArray.reduce((accumulator, currentItem, currentIndex) => {
  // 计算当前元素应该属于哪一组(每2个元素一组)
  const groupNumber = Math.floor(currentIndex / 2);
  
  // 如果这一组还没被初始化,先创建一个空数组
  if (!accumulator[groupNumber]) {
    accumulator[groupNumber] = [];
  }
  
  // 把当前元素添加到对应的组里
  accumulator[groupNumber].push(currentItem);
  
  return accumulator;
}, []);

console.log(groupedArray); // 输出: [[0, 1], [2, 3], [4, 5]]

这个思路和展平刚好相反:展平是把每个子数组合并到累加器,这里是把每个元素按索引分配到对应的子数组中。

方法2:用forEach遍历(更直观)

如果觉得reduce的逻辑有点绕,用forEach会更直白,新手也容易理解:

const originalArray = [0, 1, 2, 3, 4, 5];
const groupedArray = [];
let currentGroup = [];

originalArray.forEach((item, index) => {
  currentGroup.push(item);
  
  // 当遇到第2、4...个元素,或者遍历到数组最后一个元素时,把当前组存入结果
  if ((index + 1) % 2 === 0 || index === originalArray.length - 1) {
    groupedArray.push(currentGroup);
    currentGroup = []; // 重置临时组,准备接收下一组元素
  }
});

console.log(groupedArray); // 输出: [[0, 1], [2, 3], [4, 5]]

方法3:用slice循环截取(最简洁)

这种方法利用数组的slice方法,每次截取固定长度的片段,代码非常简洁:

const originalArray = [0, 1, 2, 3, 4, 5];
const groupSize = 2; // 你可以改成任意想要的分组长度
const groupedArray = [];

for (let i = 0; i < originalArray.length; i += groupSize) {
  // 从索引i开始,截取length为groupSize的子数组
  groupedArray.push(originalArray.slice(i, i + groupSize));
}

console.log(groupedArray); // 输出: [[0, 1], [2, 3], [4, 5]]

小提示

如果你的数组长度不是分组大小的整数倍,比如[0,1,2,3,4],这个方法会自动把最后剩下的元素单独分成一组,结果是[[0,1], [2,3], [4]],非常灵活。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 23:02:46