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

如何将API返回的一维对象数组按每3个元素分组为嵌套数组

一维数组按每3个元素分组为嵌套数组的实现方法

方法一:循环结合slice方法

通过循环遍历原数组,每次截取指定长度的子数组存入结果数组:

function groupArray(arr, groupSize) {
  const result = [];
  for (let i = 0; i < arr.length; i += groupSize) {
    result.push(arr.slice(i, i + groupSize));
  }
  return result;
}

// 调用示例
const Data = [
  {id:0, name: "name"},
  {id:1, name: "name"},
  {id:2, name: "name"},
  {id:3, name: "name"},
  {id:4, name: "name"},
  {id:5, name: "name"}
];

const groupedData = groupArray(Data, 3);
console.log(groupedData);

方法二:使用reduce方法

利用数组的reduce方法,根据元素索引计算分组位置,逐步构建嵌套数组:

const groupArray = (arr, groupSize) => {
  return arr.reduce((acc, curr, index) => {
    const groupIndex = Math.floor(index / groupSize);
    acc[groupIndex] = acc[groupIndex] || [];
    acc[groupIndex].push(curr);
    return acc;
  }, []);
};

// 调用示例
const Data = [
  {id:0, name: "name"},
  {id:1, name: "name"},
  {id:2, name: "name"},
  {id:3, name: "name"},
  {id:4, name: "name"},
  {id:5, name: "name"}
];

const groupedData = groupArray(Data, 3);
console.log(groupedData);

以上两种方法都能将原一维数组按每3个元素一组,转换为嵌套数组结构,且支持自定义分组大小(修改groupSize参数即可)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 02:45:45