Home > Software engineering >  Merging Two Ranges as One Range in Google App Script
Merging Two Ranges as One Range in Google App Script

Time:11-03

I have a google app script.

code.gs

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

  const sheetA = ss.getSheetByName("SYLLABUSC");
  const rangeA = sheetA.getRange("C1:C6");

  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("1R5Wgq4okSWz0d159X5kPvOk8W1T_6eZ2kwoq5kdjO0w");

  const sheetA = ss.getSheetByName("SYLLABUSC");
  const rangeA = sheetA.getRange("C1:C6").getDisplayValues().join("\n");

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

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


Here is My Web App

CodePudding user response:

Replace this:

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

With this:

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

CodePudding user response:

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);
}
  • Related