Ways to select specific columns instead of all columns in a dataset (Extended Inquiry)

This question is a continuation of the previous inquiry.

View Previous Question

My objective now is to tweak the answer provided earlier. Specifically, I am looking to extract only certain columns instead of all. How should I go about making this adjustment? Thank you.

Data Source: https://i.sstatic.net/yAiZy.png

Expected Outcome:

https://i.sstatic.net/8tDZT.png

Reviewing the solution from the previous question:

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 selected data:\n" + merged + "\n" + "\n";

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

Answer №1

If you're looking to modify your script, consider the following suggestion:

From:

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

To:

var columns = [6, 2, 3, 7, 5]; // This is based on your request to extract specific columns.
columns.unshift(2);
var [_, ...data] = sheet.getDataRange().getValues();
data = data.map(row => columns.map(index => row[index - 1]));

References:

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ways to retrieve an isolated scope in a directive without utilizing a template

It is clear that when I assign a controller to an element, the element along with its children can access the controller's scope. However, it is surprising that when I include a directive with an isolated scope on an element (as an attribute), I woul ...

The input 'Query' cannot be matched with the type '[(options?: QueryLazyOptions<Exact<{ where?:"

Using codegen, I've created custom GraphQL hooks and types. query loadUsers($where: UserFilter) { users(where: $where) { nodes { id email firstName lastName phoneNumber } totalCount } } export functio ...

react.js function that returns 'undefined'

Having trouble with my class function that returns undefined when I try to use the return value. Main.js: let db = new Database() let username = db.get() return( //returns undefined <p>{username}</p> ) database.js: class Database { [... ...

Select an option from the dropdown menu to populate the contents of the second dropdown list

The provided code dynamically populates the initial dropdown list with unique pants brands: $.each(pantsBrands, function(i){ var li = $('<li>') .appendTo(pantsList); var aaa = $('<a>') .text(pantsBra ...

Animated dropdown feature spanning the entire width of the screen

I successfully developed a basic dropdown menu with full-width sub-menu functionality. Check it out on jsFiddle: $(document).ready(function(){ $(".drop").hide(); $(".link-1").mouseenter(function(){ $('.link-1-drop').slide ...

Exploring the dynamic interaction between JavaScript and PHP for defining variables on a webpage

Below is the code snippet where I have utilized the load function to auto-refresh timing.php. <script> var auto_refresh = setInterval(function() { $('#myDiv').load('timing.php?test=<?php echo $test?>'); }, 1000); </scrip ...

"Exploring the Latest Features of NextJS 13: Enhancing Server

Currently, I am in the process of familiarizing myself with NextJS 13 and its new APP folder structure. I am facing a challenge in updating data on server components without needing to reload the page or the app. My HomePage server component fetches a list ...

Passing information from a Node.js backend to a frontend JavaScript

I am currently facing challenges in passing variables from my NodeJS backend to a JS script. The backend code snippet resembles the following: app.js const express = require('express'); const app = express(); const path = require('path&apos ...

Optimizing table resizing for improved speed in electron application

In my electron app, I've implemented the following JavaScript function to resize table columns: const resizerMouseDown = (e) => { let th = e.target.parentNode let startOffset = th.offsetWidth - e.x window.addEventListener('mousemo ...

Can dark mode be activated and maintained across multiple pages using just one JavaScript file?

I'm facing an issue with maintaining a dark mode across multiple web pages. I tried adding a JavaScript script to all my HTML files, but it didn't work as expected. Then, I experimented by adding the script to just one HTML file, and while it suc ...

Unable to create scrolling functionality for the div in Bootstrap

I'm working with a code that includes a text input for users to enter information, along with a panel above the text input that displays what the user has typed. I want the height of the panel above the text field to be set so that it becomes scrollab ...

Tips for enhancing the transition effect of animated gifs on a webpage using JavaScript

In my code, I have an interval set to run every seven seconds. Within this interval, there are two gifs that each last for seven seconds. My goal is to display one of the gifs in a div (referred to as "face") based on certain conditions - for example, if t ...

The jstree does not seem to be generating the tree structure as expected based on

I am utilizing the jstree plugin to construct a hierarchical tree view of locations, rooms, and assets for a company within a PHP application that I am developing. The main intention behind this tree is to enable users to select an asset while going throu ...

Remove a record from the EntityFramework database using ajax

I am a beginner and facing an issue with deleting records from the database using JavaScript, Ajax, and Json in MVC Entity Framework. My delete button seems to be malfunctioning. In my controller class, the action code is as follows: public ActionResult ...

The request body is unable to interpret inputs coming from an array of name attributes

I am encountering issues with a form that contains arrays in the name attribute. Currently, there are two specific problems I am facing. (1) After submitting the form, I am unable to extract and process the values stored within itemName[], itemValue[], an ...

Can you explain the significance of this error message that occurs when attempting to execute a node.js script connected to a MySQL database?

const mysql = require('mysql'); const inquirer = require('inquirer'); const connection = mysql.createConnection({ host: "localhost", port: 8889, user: "root", password: "root", database: "bamazon" }) connection.conn ...

What is the best way to construct an array in JavaScript using a loop and JSON AJAX for the "key" value pair?

Trying to update a vector map using values fetched through AJAX and JSON. The map works perfectly with this key-value array: var visitorsData = { "tac": 564, "moq": 400, "lim": 1000, "apu": 800, "caj": 760, "ama": 300, " ...

Unable to locate the module '../build/Release/bson' with error code 'MODULE_NOT_FOUND'. The js-bson module failed to load the c++ bson extension and will resort to using the pure JS version

I encountered the following error: { [Error: Module not found '../build/Release/bson'] code: 'MODULE_NOT_FOUND' } js-bson: C++ bson extension failed to load, using pure JS version Here are the details of my versions: Operating ...

Creating a live notification in the chat that displays "User is typing" to all participants

I am working on developing a chat application using jQuery and PHP. I am looking for guidance on how to implement a feature where a user, let's say "Evx," types a message in real-time and it is instantly displayed to all other users. This functionalit ...

The issue with VueJs arises when a basic v-if statement is utilized for computeds and fails

When using a simple v-if in Vuejs, the following code is used: <span v-if="!profile_full_name===''"> @{{ profile_full_name }} </span> <span v-else> {{auth()->user()->fullName}} </span> In this ...