Skip to content

Instantly share code, notes, and snippets.

@MauricioMoraes
Created October 22, 2015 12:00
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save MauricioMoraes/225afcc9dd72acf1511f to your computer and use it in GitHub Desktop.
Save MauricioMoraes/225afcc9dd72acf1511f to your computer and use it in GitHub Desktop.
Javascript Flatten (for one level nested arrays) - Useful for google apps scripts on spreadsheets
// Takes and array of arrays matrix and return an array of elements.
function flatten(arrayOfArrays){
return [].concat.apply([], arrayOfArrays);
}
@MauricioMoraes
Copy link
Author

Example:

arrayOfArrays = [ [1], [2,3], [4], [5,6] ]
flatten(arrayOfArrays) // returns: [1, 2, 3, 4, 5, 6]

Example 2:

arrayOfArraysWithTwoLevelNesting = [ [1], [[2],3], [4], [[5],6] ]
flatten(flatten(arrayOfArraysWithTwoLevelNesting )) // returns: [1, 2, 3, 4, 5, 6]

@MauricioMoraes
Copy link
Author

Example for google spreadsheets: To get all column header names:

  var thisSpreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = thisSpreadsheet.getSheetByName(name);
  var columnHeaderNamesRange = sheet.getRange(A2:Z2); // getValues on this range returns an array of arrays
  var allColumnNames = flatten(columnHeaderNamesRange.getValues());

@illia108
Copy link

illia108 commented May 2, 2019

Good one. Thanks. Do you know why flat() doesn't work in google apps script?

@John-Dox
Copy link

thanks

@mommalibrarian
Copy link

The before and after arrays look the same in Logger.log. How can you tell they have changed?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment