LANG SELRCT

Apps Script Reference  (Create: Create new Spreadsheet | Create new Apps Script

Tuesday, December 10, 2019

JSで配列から空の要素を除きたい


このような配列を

[1, 2, , 3, 4, '', , , , 5]


こうしたい

[1, 2, 3, 4, 5]





コード.gs
function myFunction() {
  var array = [1, 2, , 3, 4, '', , , , 5];
  var resultArray = array.filter(function(value) { return value !== ''; });
  Logger.log(resultArray)
}



別の書き方

コード.gs
function myFunction() {
  var array = [1, 2, , 3, 4, '', , , , 5];
  var resultArray = array.filter(removeBlank);
  Logger.log(resultArray)
}


function removeBlank(value) {
    return value !== '';
}


別の書き方

コード.gs
function myFunction() {
  var array = [1, 2, , 3, 4, '', , , , 5];
  var resultArray = array.filter(removeBlank);
  Logger.log(resultArray)
}


function removeBlank(value) {
  if(value) {
    return value;
  }
}



Latest post

Extracting data from Google Sheets with regular expressions

Introduction Regular expressions are a powerful tool that can be used to extract data from text.  In Google Sheets, regular expressions ca...