Prabhu Paul
Prabhu Paul

Reputation: 188

Merging Two Ranges as One Range in Google App Script

I have a google app script.

code.gs

const doGet = _ => {
  
  const ss = SpreadsheetApp.openById("1FJtOQZAN_SIOYHybA9FXbJ_ngoRy38KTvo1hZu7SEUs");

  const sheetA = ss.getSheetByName("SYLLABUSC");
  const rangeA = sheetA.getRange("E1:E5");

  const sheetB = ss.getSheetByName("SHEETB");
  const rangeB = sheetB.getRange("A1:A3");

  const html = rangeA.getDisplayValues().join("\n");
  
  return ContentService.createTextOutput(html).setMimeType(ContentService.MimeType.JAVASCRIPT);
}


By above I'm getting TextOutput from SheeA Range only.

But I want both ranges one by one, i.e. SheetA Range and then SheetB Range.

How to merge these ..?

Update :

By the Answer provided, the Code.gs file modified like below.

const doGet = _ => {
  
  const ss = SpreadsheetApp.openById("1FJtOQZAN_SIOYHybA9FXbJ_ngoRy38KTvo1hZu7SEUs");

  const sheetA = ss.getSheetByName("SYLLABUSC");
  const rangeA = sheetA.getRange("E1:E5").getDisplayValues();

  const sheetB = ss.getSheetByName("SHEETB");
  const rangeB = sheetB.getRange("A1:A3").getDisplayValues();

  const html = rangeA.concat(rangeB).join("\n");
  
  return ContentService.createTextOutput(html).setMimeType(ContentService.MimeType.JAVASCRIPT);
}

Here is My Web App

Upvotes: 0

Views: 1296

Answers (2)

Cooper
Cooper

Reputation: 64062

Merge Ranges:

function mergeRanges() {
  const ss = SpreadsheetApp.openById("1R5Wgq4okSWz0d159X5kPvOk8W1T_6eZ2kwoq5kdjO0w");
  const sheetA = ss.getSheetByName("SYLLABUSC");
  const vsa = sheetA.getRange("C1:C6").getDisplayValues();
  const sheetB = ss.getSheetByName("SHEETB");
  const vsb = sheetB.getRange("A1:A3").getDisplayValues();
  const html = [vsa, vsb].reduce((a, c, i) => {
    c.forEach(arr => a += arr.join('\n'))
    return a;
  }, "")
  Logger.log(html);
  return ContentService.createTextOutput(html).setMimeType(ContentService.MimeType.JAVASCRIPT);
}

Upvotes: 1

TheWizEd
TheWizEd

Reputation: 8596

Replace this:

const html = rangeA.getDisplayValues().join("\n");

With this:

let html = rangeA.getDisplayValues().concat(rangeB.getDisplayValues());
html = html.join("\n");

Upvotes: 2

Related Questions