結論
const arr = [1,2,3,4,5,6,7,8,9];
const divideNum = 3;
const result = arr.flatMap((_, i, a) => {
if (i % divideNum === 0) return [a.slice(i, i+divideNum)];
return [];
});
// result = [[1,2,3],[4,5,6],[7,8,9]];
仕組み
- 配列のindexで処理を分岐(配列を分割した二重配列or空配列)
- flat()により階層を1つ上げる
おわりに
- flatMap() はmap() + flat()の機能
- flatMapの方が若干パフォーマンスが良い
- 引数はmapと同じ(要素・インデックス・呼び出した配列)
別解
※コメントより(@oswe99489 さん)
const arrayDivide = (arr, divideNum) => {
const result = [];
const t = arr.slice();
while (t.length && divideNum >= 1) result.push(t.splice(0, divideNum));
return result;
};
const arr = [1,2,3,4,5,6,7,8,9];
console.log(arrayDivide(arr, 3)); // [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ]
console.log(arrayDivide(arr, 4)); // [ [ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ], [ 9 ] ]
console.log(arrayDivide(arr, 0)); // []
参考