LoginSignup
4
2

More than 5 years have passed since last update.

【JavaScript】管理しやすい二次元配列の組み方

Posted at

【JavaScript】管理しやすい二次元配列の組み方

JavaScriptでCSVファイルを読み込んで何かするときに、良い感じの組み方を考えてみました。

  1. インデックスの作成
  2. 二次元配列の構成
  3. 二次元配列の使い方
  4. まとめ

インデックスの作成

sample.js

const index = {
  number: 0,
  string: 1,
  boolean: 2
}

CSV側で列が変更されたときにも対応するためインデックスを作成する。

二次元配列の作成

sample.js

const index = {
  number: 0,
  string: 1,
  boolean: 2
}

//------------ ▼ 追加 ▼ ------------
const array = [
  [ 0, 'Hello HTML/CSS', false ],
  [ 1, 'Hello JavaScript', true ],
  [ 2, 'Hello TypeScript', false ],
  [ 3, 'Hello Node.js', true ]
]

こんな感じに組むと、行と列がわかりやすい。

二次元配列の使い方

sample.js

const index = {
  number: 0,
  string: 1,
  boolean: 2
}

const array = [
  [ 0, 'Hello HTML/CSS', false ],
  [ 1, 'Hello JavaScript', true ],
  [ 2, 'Hello TypeScript', false ],
  [ 3, 'Hello Node.js', true ]
]

//------------ ▼ 追加 ▼ ------------
for ( let i = 0; i < array.length; i++ ) {
  const number = `number: ${array[i][index.number]} \n`;
  const string = `string: ${array[i][index.string]} \n`;
  const boolean = `boolean: ${array[i][index.boolean]} \n`;
  console.log( number + string + boolean );
}
/* consoleの結果 */

  number: 0 
  string: Hello HTML/CSS 
  boolean: false 

  number: 1 
  string: Hello JavaScript 
  boolean: true 

  number: 2 
  string: Hello TypeScript 
  boolean: false 

  number: 3 
  string: Hello Node.js 
  boolean: true 

iで行を選択して、indexで列を選択する。

まとめ

インデックスを作成すると、配列に何が入っているかわかりやすくなる。
例:array[i][0]array[i][index.number]

配列を使うときの参考になればと思います。

4
2
0

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
4
2