Google Apps ScriptでgetValuesの2次元配列を1次でまとめる方法

getValues()とは

getValues()は指定した範囲の値を2次元配列で返す。

例えば下図の場合はsheet.getRange('A1:B5').getValues();で取得すると、以下のように2次元配列で取得できる。

function myFunction() {
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const sheet = ss.getSheets()[0];
  const result = sheet.getRange('A1:B5').getValues();
  Logger.log(result);
  // [[foo, ], [bar, ], [baz, hoge], [, fuga], [, ]]
  
  Logger.log(result[2][1]);
  // hoge
}

2次元配列を1次元配列にまとめる

前述のようにresult[2][1]のようにして特定の値を指定したい場合は2次元配列でも良いが、1つのまとまったデータとして取り扱いたい場合は[foo, bar, baz, hoge, fuga]のような空の値を除外した1次元配列のほうが都合が良い。

1次元配列にまとめたい場合はgetValues()で取得したあとにflat().filter(String).map(String)を続けて処理すれば取得できる。

function myFunction() {
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const sheet = ss.getSheets()[0];
  const result = sheet.getRange('A1:B5').getValues().flat().filter(String).map(String);
  Logger.log(result);
  // [foo, bar, baz, hoge, fuga]
}