javascript - JS 将数组拆分为 X 个 block ,然后是 Y 个 block ,依此类推

标签 javascript arrays typescript grouping

我到底如何将一个数组分成 6 个 block ,然后是 3 个 block ,然后是 6 个 block ,然后是 3 个 block ,依此类推?

假设我有这个数据集:

const datasaet = [
  { text: 'hi1' },
  { text: 'hi2' },
  { text: 'hi3' },
  { text: 'hi4' },
  { text: 'hi5' },
  { text: 'hi6' },
  { text: 'hi7' },
  { text: 'hi8' },
  { text: 'hi9' },
  { text: 'hi10' },
  { text: 'hi11' },
  { text: 'hi12' },
  { text: 'hi13' },
  { text: 'hi14' },
  { text: 'hi15' },
  { text: 'hi16' },
]

我需要将它分成一个数组,如下所示:

const expected = [
  [
    { text: 'hi1' },
    { text: 'hi2' },
    { text: 'hi3' },
    { text: 'hi4' },
    { text: 'hi5' },
    { text: 'hi6' },
  ],
  [
    { text: 'hi7' },
    { text: 'hi8' },
    { text: 'hi9' },
  ],
  [
    { text: 'hi10' },
    { text: 'hi11' },
    { text: 'hi12' },
    { text: 'hi13' },
    { text: 'hi14' },
    { text: 'hi15' },
    { text: 'hi16' },
  ]
]

本质上,我正在做的是将数组分成 6 个 block (如果是事件)和 3 个 block (如果是奇数)。

但是我不知道该怎么做。我当前的尝试看起来像这样,我可以将它完美地分成 6 block ,但是我该如何去做接下来的 3 block ,然后是接下来的 6 block ,依此类推:

const grouped = datasaet.reduce(
  (initital: any[], current, index, items) => {
    const isFirstOfSix = index % 6 === 0
    if (isFirstOfSix) {
      const nextSix = items.slice(index, index + 6)
      initital.push(nextSix)
    }

    return initital
  },
  []
) 

最佳答案

您可能会考虑创建数组的副本(以避免改变原始数组),然后拼接项目直到其为空,检查并切换一个 bool 值以指示是否在当前迭代中删除 6 个或 3 个项目:

const datasaet = [
  { text: 'hi1' },
  { text: 'hi2' },
  { text: 'hi3' },
  { text: 'hi4' },
  { text: 'hi5' },
  { text: 'hi6' },
  { text: 'hi7' },
  { text: 'hi8' },
  { text: 'hi9' },
  { text: 'hi10' },
  { text: 'hi11' },
  { text: 'hi12' },
  { text: 'hi13' },
  { text: 'hi14' },
  { text: 'hi15' },
  { text: 'hi16' },
]

const tempArr = datasaet.slice();
const output = [];
let removeSix = true;
while (tempArr.length) {
  output.push(tempArr.splice(0, removeSix ? 6 : 3));
  removeSix = !removeSix;
}
console.log(output);

关于javascript - JS 将数组拆分为 X 个 block ,然后是 Y 个 block ,依此类推,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58353793/

相关文章:

typescript - 如何在 WebStorm/PhpStorm 中自动按字母顺序对 TypeScript 文件的导入进行排序?

带 ctrl 的 Angular 向上箭头

javascript - HTML5 视频标签在移动设备上不起作用

javascript - 使用谷歌图表在单个图表中显示多条线图

arrays - 检查数组是否包含实例变量 Ruby 具有特定值的实例

python - 将 numpy 多维数组转换为列表

php - 在 ul 中输出每个数组

javascript - 如何在谷歌地图的屏幕中心设置标记

javascript - json_encode 和 JSON.parse 不协调

javascript - 在javascript中多次使用一种方法