将Javascript数组元素拆分为指定索引处的块

dte*_*lus 0 javascript arrays split

我有一个像这样的数组

const arr = [3,6,9,12,18,21,24,27,33,36];
Run Code Online (Sandbox Code Playgroud)

我希望将数组arr分成12、21和33的块。即在索引3、5和8处。我想生成另一个像这样的数组

const chunks = [[3,6,9,12],[18,21],[24,27,33],[36]];
Run Code Online (Sandbox Code Playgroud)

我在这里看到的解决方案基本上将数组拆分为“ n”个块。基本上我想在几个(指定)索引处拆分数组。

我不介意underscore.js / lodash解决方案。谢谢

Seb*_*mon 5

您可以使用reduceRight并决定拆分哪些元素。由于您提供的是子数组的最后一个值而不是一个值,因此从右向左移动实际上会更容易一些,因此我使用了reduceRight而不是a reduce

按价值划分

const arr = [3, 6, 9, 12, 18, 21, 24, 27, 33, 36],
  splitValues = [12, 21, 33],
  chunks = arr.reduceRight((result, value) => {
    result[0] = result[0] || [];

    if (splitValues.includes(value)) {
      result.unshift([value]);
    } else {
      result[0].unshift(value);
    }

    return result;
  }, []);

console.log(chunks);
Run Code Online (Sandbox Code Playgroud)
.as-console-wrapper { max-height: 100% !important; top: 0; }
Run Code Online (Sandbox Code Playgroud)

按指数划分

const arr = [3, 6, 9, 12, 18, 21, 24, 27, 33, 36],
  splitIndexes = [3, 5, 8],
  chunks = arr.reduceRight((result, value, index) => {
    result[0] = result[0] || [];

    if (splitIndexes.includes(index)) {
      result.unshift([value]);
    } else {
      result[0].unshift(value);
    }

    return result;
  }, []);

console.log(chunks);
Run Code Online (Sandbox Code Playgroud)
.as-console-wrapper { max-height: 100% !important; top: 0; }
Run Code Online (Sandbox Code Playgroud)