二次元配列の初期化【JavaScript】

二次元配列の配列リテラルによる初期化

const array = [
  [1, 2, 0, 0, 0, 0, 0, 0, 0, 0],
  [3, 0, 0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
];
console.log(array);
// (5) [Array(10), Array(10), Array(10), Array(10), Array(10)]
// 0: (10) [1, 2, 0, 0, 0, 0, 0, 0, 0, 0]
// 1: (10) [3, 0, 0, 0, 0, 0, 0, 0, 0, 0]
// 2: (10) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
// 3: (10) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
// 4: (10) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

二次元配列の初期化

/**
 * 二次元配列の作成
 * @param {integer} N - 行数
 * @param {integer} M - 列数
 * @param {*} [value=0] - 初期化する値
 * @return {Array} 作成した二次元配列
 */
function create2DArray(N, M, value) {
  const val = value !== void 0 ? value : 0;
  const array = [];//new Array(N);
  for(let r=0; r<N; r++) {
    array[r] = [];//new Array(M);
    for(let c=0; c<M; c++) {
      array[r][c] = val;
    }
  }
  return array;
};

ワンライナー版

const create2DArray = (N, M, value=0) => Array.from({length:N}, _ => new Array(M).fill(value));

使用例

console.log(create2DArray(5, 10));
// (5) [Array(10), Array(10), Array(10), Array(10), Array(10)]
// 0: (10) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
// 1: (10) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
// 2: (10) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
// 3: (10) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
// 4: (10) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

var a = create2DArray(5, 10, 9);
a[0][0] = 1;
a[0][1] = 2;
a[1][0] = 3;
console.log(a);
// (5) [Array(10), Array(10), Array(10), Array(10), Array(10)]
// 0: (10) [1, 2, 9, 9, 9, 9, 9, 9, 9, 9]
// 1: (10) [3, 9, 9, 9, 9, 9, 9, 9, 9, 9]
// 2: (10) [9, 9, 9, 9, 9, 9, 9, 9, 9, 9]
// 3: (10) [9, 9, 9, 9, 9, 9, 9, 9, 9, 9]
// 4: (10) [9, 9, 9, 9, 9, 9, 9, 9, 9, 9]

備考

一次元配列の初期化const create1DArray = (N, value=0) => new Array(N).fill(value);
三次元配列の初期化const create3DArray = (N, M, L, value=0) => Array.from({length:N}, _ => Array.from({length:M}, __ => new Array(L).fill(value)));

二次元配列の文字列からの初期化

空白区切りconst input = `1 2 3 4 5
11 12 13 14 15
21 22 23 24 25`;
const array = input.split('\n').map(v => v.split(' ').map(Number));
console.log(array);
// (3) [Array(5), Array(5), Array(5)]
// 0: (5) [1, 2, 3, 4, 5]
// 1: (5) [11, 12, 13, 14, 15]
// 2: (5) [21, 22, 23, 24, 25]
カンマ区切りconst input = `1,2,3,4,5
11,12,13,14,15
21,22,23,24,25`;
const array = input.split('\n').map(v => v.split(',').map(Number));
console.log(array);
// (3) [Array(5), Array(5), Array(5)]
// 0: (5) [1, 2, 3, 4, 5]
// 1: (5) [11, 12, 13, 14, 15]
// 2: (5) [21, 22, 23, 24, 25]