Home > Software engineering >  How to take only a few of the column and not all of the column (Extended Question)
How to take only a few of the column and not all of the column (Extended Question)

Time:01-17

This question is the extended from the previous question.

enter image description here

The Expected result:

enter image description here

Here is the previous question's answer:

function myFunction() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName('sheetName');

  var [_, ...data] = sheet.getDataRange().getValues();
  const order = ['First', 'Second', 'Third']
  const sorted = data.sort((a, b) => {
    const i1 = order.indexOf(a[0]);
    const i2 = order.indexOf(b[0]);
    const len = data.length;
    return 1 * ((i1 > -1 ? i1 : len) - (i2 > -1 ? i2 : len));
  });
  const merged = sorted.reduce((o, [a, ...b]) => {
    if (o.temp != a) {
      o.merged.push(a);
      o.temp = a;
    }
    o.merged.push(`- ${b.join(",")}`);
    return o;
  }, { merged: [], temp: "" }).merged.join("\n");

  console.log(merged)
  var email = ''
  var Subject = "data";
  var Message = "Hello ", \n"   "\n"  
    "Here is the list of data:\n"   merged   "\n"   "\n";

  MailApp.sendEmail(email, Subject, Message);
}

CodePudding user response:

In your script, how about the following modification?

From:

var [_, ...data] = sheet.getDataRange().getValues();

To:

var columns = [6, 2, 3, 7, 5]; // This is from your comment of "I want to take Column 6, Column 2, Column 3, Column 7, and Column 5 to as Expected result's data".
columns.unshift(2);
var [_, ...data] = sheet.getDataRange().getValues();
data = data.map(r => columns.map(f => r[f - 1]));

References:

  • Related