这里有一个更具体的案例,有人可能会发现它很有价值。我还没有看到这里提到过。
如果您不想要恒定/均匀的块大小,而是想要指定拆分数组的索引,该怎么办。在这种情况下,您可以使用:
const splitArray = (array = [], splits = []) => {
array = [...array]; // make shallow copy to avoid mutating original
const chunks = []; // collect chunks
for (const split of splits.reverse()) chunks.push(array.splice(split)); // go backwards through split indices and lop off end of array
chunks.push(array); // add last remaining chunk (at beginning of array)
return chunks.reverse(); // restore chunk order
};
然后:
splitArray([1, 2, 3, 4, 5, 6, 7, 8, 9], [4, 6])
// [ [1, 2, 3, 4] , [5, 6] , [7, 8, 9] ]
请注意,如果你给它非升序/重复/负/非整数/等拆分索引,这会做一些有趣的事情。您可以为这些边缘情况添加检查(例如 Array.from(new Set(array)) 以进行重复数据删除。