Search code examples
google-apps-scriptgoogle-sheets

How to merge multiple column data row by row in google sheet


I'm trying to combine three data column into one like the sample in the link i put below

https://docs.google.com/spreadsheets/d/1mhYemGjgoRJDb7drNN36g7MuNDDmynR3v6l3kgn8da8/edit#gid=0

enter image description here

thanks for reading.

input is the three data column, with each row in one of three data can contain value, output is the combination of these column


Solution

  • From your sample input and output situations and input is the three data column, with each row in one of three data can contain value, output is the combination of these column in your question, how about the following sample script?

    Sample script 1:

    In this sample script, it supposes that the number value is not included in the cells.

    function sample1() {
      const sheetName = "S1"; // Please set your sheet name.
    
      const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName);
      const richTextValues = sheet.getRange("A2:C" + sheet.getLastRow()).getRichTextValues().map(r => [r.find(e => e.getText()) || SpreadsheetApp.newRichTextValue().setText("").build()]);
      sheet.getRange(2, 4, richTextValues.length).setRichTextValues(richTextValues);
    }
    
    • When this script is run, the values are retrieved from columns "A" to "C" and the result is put into column "D".

    Sample script 2:

    In this sample script, it supposes that the number value might be included in the cells.

    function sample2() {
      const sheetName = "S1"; // Please set your sheet name.
    
      const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName);
      const range = sheet.getRange("A2:C" + sheet.getLastRow());
      const values = range.getDisplayValues();
      const richTextValues = range.getRichTextValues().map((r, i) => {
        const idx1 = r.findIndex(e => e.getText());
        const idx2 = values[i].findIndex(e => e);
        return [idx1 != -1 ? r[idx1] : SpreadsheetApp.newRichTextValue().setText(values[i][idx2] || "").build()];
      });
      sheet.getRange(2, 4, richTextValues.length).setRichTextValues(richTextValues);
    }
    
    • When this script is run, the values are retrieved from columns "A" to "C" and the result is put into column "D".

    Note:

    • These scripts can be used for your provided Spreadsheet. When you change the Spreadsheet, these might not be able to be used. Please be careful about this.

    • If the above scripts were not useful for your actual situation, please provide more samples. By this, I would like to modify the script.

    References: