0
0

配列を任意の個数で分割した新しい二次元配列を作る(JavaScript)

Last updated at Posted at 2024-08-06

結論


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]];

仕組み

  1. 配列のindexで処理を分岐(配列を分割した二重配列or空配列)
  2. 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)); // []

参考

0
0
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0