How can I modify this section of the code in Google Script to retrieve all columns?

My question is, how can I modify this code to fetch all columns from the array instead of just [0,1,2,3]

Here is the line of code in question:

const new_table = [0,1,2,3].map(x => make_row_from_col(this_table, x)).join('\n');

Using object.keys(this_table) does NOT work as it only displays 4 rows.

Here is the complete script:

function Test() {
  
  const sSheet   = SpreadsheetApp.getActiveSpreadsheet();
  const srcSheet = sSheet.getSheetByName("Refinery");
  const table    = srcSheet.getRange("A:H").getValues(); // use "D2:M" if you have a header
  
  const values_C = table.filter(t => t[7] == "READY TO SELL").map(t => t[0]);
  const values_D = table.filter(t => t[7] == "READY TO SELL").map(t => t[1]);
  const values_E = table.filter(t => t[7] == "READY TO SELL").map(t => t[2]);
  const values_F = table.filter(t => t[7] == "READY TO SELL").map(t => t[3]);
 
  
  Logger.log(values_C)
  Logger.log(values_D)
  Logger.log(values_E)
  Logger.log(values_F)
  Logger.log(values_C.length)
      

      const this_table = [values_C,values_D,values_E,values_F];
      const make_row_from_col = (this_table, col) => this_table.map(x => x[col]).join("\t"+"\t" + "  |  "+"\t"+"\t");
      const new_table = Object.keys(this_table).map(x => make_row_from_col(this_table, x)).join('\n');
      
      Logger.log(new_table);
}

THIS IS THE TABLE https://i.sstatic.net/Pt81F.png

Here is the LOG of the script and the desired output: https://i.sstatic.net/QLG7P.png

Answer №1

Problem Description:

Object.keys returns an array of indexes when applied to an array. Using it on this_table will result in an array with 4 items, as that is the length of this_table.

Consequently, you are only seeing 4 rows displayed for your "table".

Proposed Solution:

An alternative and more efficient approach would be to extract the values from the 4 desired columns at once, and then utilize the join method on them:

const values = table.filter(t => t[7] == "READY TO SELL").map(t => t.slice(0,4));
const new_table = values.map(this_row => this_row.join("\t"+"\t"+"  |  "+"\t"+"\t")).join("\n");

If you prefer to retrieve the columns separately, you could consider transposing the resulting 2D array so that the inner arrays represent rows rather than columns. Refer to this solution for guidance on how to transpose an array. However, I recommend sticking with the existing data organization provided by getValues() since it aligns with your desired structure. Even if the desired columns are not consecutive, you can easily filter them within a single 2D array.

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

When attempting to modify the state in a parent component from a child using the composition API in Vue 3, the error "this.$emit() is not a

//Main component <template> <childComponent @onChangeData='updateData' /> </template> <script> setup() { const state = reactive({ data: 'example' }); function updateData(newValue){ s ...

What is the process for attaching an event handler to an element that is displayed after a button click?

I need some assistance with my JavaScript code. I have a page with two links, and when the second link is clicked, certain fields are displayed. I am trying to write an onkeyup() event handler for one of these fields, but seem to be missing something. Here ...

Resizing svg to accommodate a circle shape

As I work on my vue.js app that involves a plethora of diverse icons, I made the decision to create a small icons builder in node.js. The purpose is to standardize their usage and also "crop" each SVG so it fits perfectly within its parent container by uti ...

Tips for locating a value that differs from an item in a v-autocomplete box

I am using a v-autocomplete component: <v-autocomplete v-model="fromPrice" :items="listOfFromItems" dense solo label="from" hide-detail ...

Tips on retrieving and showcasing information from various endpoints in React?

I am working with two different endpoints and I need to fetch data from both simultaneously in order to display it in one single element. For example, I want to show data from one table along with the corresponding name from another table if the product id ...

Calculate the sum of the products when multiplying two values from every array of objects, using Reactjs/Javascript

I'm currently developing an eCommerce application and need to calculate the total price of items that users have ordered. I have an array named 'orders' which contains all the ordered items, each item has two keys - payablePrice and purchase ...

Struggling to create a foreach loop for a multi-dimensional array containing StdClass Objects

Currently, I am diving into PHP and CodeIgniter with little experience in modern programming. Thus, I would appreciate any kind guidance you could offer! I recently crafted a function to compute weekly totals of kilometers cycled on a bike from a MySQL ta ...

Timing of Bindings in AngularJS

In my setup, I have a controller that calls a service to retrieve a list of categories: $scope.enquiryCategories = CategoryServices.listCategories(); The service then fetches this data from an external API: listCategories: function () { return $http({ ...

Switching Story Tense on Facebook Open Graph

After creating a unique story for my facebook app, I discovered that when making a basic story post using the facebook js sdk, the resulting post is in past tense and depicts the object in singular form. For example, instead of saying: John is eating an a ...

"Silent Passageway: Connecting Node JS to ASW RDS MySQL Through a Secret

I am currently collaborating on a project with a partner. The backbone of our project is node js, and we are using an AWS RDS MySQL DB for our database. Our main challenge lies in establishing effective communication with the DB through SSH within NodeJS. ...

Storing a class method in a variable: A guide for JavaScript developers

I am currently working with a mysql connection object called db. db comes equipped with a useful method called query which can be used to execute sql statements For example: db.query('SELECT * FROM user',[], callback) To prevent having to type ...

Ways to conceal a div using jQuery when the video source is missing

If there is no source in the video, I want to hide the video_wrapper class <div class="video_wrapper" style="width: 100%; height: 100%; display: none;"> <video id="df-video" playsinline="" webkit-playsinline="" style="height: 100%; width: 100%; ...

Showing the previous value in the Select2 select function

I have integrated Select2 as a searching dropdown feature on my website, but I am facing an issue where the previously selected value keeps being displayed even after selecting a new item from the list. Initially, I initialize the Select2 dropdown like th ...

The beforePopState event in next/router is not triggering as expected

Noticing an issue where the beforePopState event is not triggering when I use the back button. This code snippet is part of a hook defined in _app.js according to the documentation. The current version being used is 12.1.5 If anyone has insights on what ...

Creating an HTML table using an array of objects

I'm currently working on creating a function that will generate an HTML table from an array of objects. The array provided below is what I need to convert into a table. let units = [ { 'code': 'COMP2110', &apos ...

What is the solution for fixing the [$injector:unpr] error in AngularJS?

I've recently started learning AngularJS and I'm encountering an issue with injecting a service from another file. Despite trying various methods, nothing seems to be working. Here's a snippet from my index.html: ` <!DOCTYPE html> &l ...

Setting up Nest JS by installing necessary packages

I created a package for my project and successfully installed it in my repository. However, I am facing an issue where I cannot import the functions from that package. "compilerOptions": { "module": "commonjs", " ...

Error: Trying to play the Snake Game with the P5.js Library, but getting the message "(X)

During my journey of coding a snake game by following a tutorial, I encountered an issue that the instructor had not faced before. Strangely enough, I am unable to identify the root cause of this problem. To aid in troubleshooting, I meticulously commente ...

How can Ext JS 4 handle the transmission of multiple metaData to support multiple dynamic grids by utilizing a single JSON file?

Looking to create multiple grids on a single panel using an accordion layout? I'll be dynamically generating all the grids based on metaData in JSON and handling metachange listener events on my store to reconfigure the grid. But here's the quest ...

Encountering difficulties in accessing files displayed by serve-index in Express

My Node.js server using Express seems to be working fine for displaying directory contents, but I'm running into an issue when trying to access individual files. After clicking on a file listed in the directory, I keep getting an error message that sa ...