Tips for generating arrays using cell data from Google Sheets

I am currently working on extracting information from a Google Sheet to create a list of (4X1) arrays.

   A        B    C      D       E     F      G      H      I     J 
Project | Per1 | W1 |  Team1 | Per2 | W2 | Team2 | Per3 | W3 | Team3|
—————————————————————————————————————————————————————————————————————
   p1   | Bill | .5 |  Tech  | Alice|  1 | Other |      |    |      |
   p2   |Larry |  1 |  Tech  | Bill |  1 | Other | Tina | 1  | Other|
   p3   | Joe  |  2 |  Tech  | Beth |  1 | Tech  |      |    |      |
   p4   |Kathy | .5 |  Tech  |      |    |       |      |    |      |
   p5   | Bill | 1  |  Tech  | Larry|  1 | Other |      |    |      |

*Due to constraints, I am unable to post images at the moment.

Currently, my script allows me to generate a list of (3x1) arrays:

 function arrayOfObjects() {
  var ss=SpreadsheetApp.getActive();
  var sh=ss.getSheetByName('Sheet1');
  var vA=sh.getRange("B2:D6").getValues();
  Logger.log(vA);
}

The current results are as follows:

 [[Bill, 0.5, Tech], [Larry, 1.0, Other], [Joe, 2.0, Tech], [Kathy, 0.5, Other], [Alice, 1.0, Tech]]

However, this only covers the range B2:D6

I am looking to establish links between names and projects (p1,p2,... for further analysis). I aim for the final output to be in the form of (4X1) arrays:

[[p1,Bill,.5,Tech], [p1,Alice,1,Other],[p2,Larry,1,Other],[p2,Bill,.5,Other],
[p2,Tina,1,Other]........[p5,Larry,1,Other]]

Eventually, I want to present the data in table format:

    A           B                         
| Name | Number Of project|  
———————————————————————————
| Bill |        3         |
|Larry |        2         |
| Joe  |        1         |   
|Kathy |        1         |
| Alice|        1         |
   etc...

Answer №1

Exploring 1x4 Arrays and Objects

In this tutorial, you will learn how to generate 1x4 arrays and objects. It's up to you to choose which one fits your needs.

function extractProjectInfo() {
  var ss=SpreadsheetApp.getActive();
  var sh=ss.getSheetByName('Projects');
  var rg=sh.getDataRange();
  var vA=rg.getValues();
  var projArray=[];
  var projObject=[];
  for(var i=1;i<vA.length;i++) {
    for(var j=1;j<vA[i].length;j+=3) {
      if(vA[i][j] && vA[i][j+1] && vA[i][j+2]) {
        projArray.push([vA[i][0],vA[i][j],vA[i][j+1],vA[i][j+2]]);
        projObject.push({project:vA[i][0],person:vA[i][j],weight:vA[i][j+1],team:vA[i][j+2]}); 
      }
    }
  }
  var resultObj={array:projArray,object:projObject};
  return resultObj;
}

This version allows you to view them in a dialog box and demonstrates how you can access them using either indices or keys.

function displayProjectInfo() {
  var ss=SpreadsheetApp.getActive();
  var sh=ss.getSheetByName('Projects');
  var rg=sh.getDataRange();
  var vA=rg.getValues();
  var projArray=[];
  var projObject=[];
  for(var i=1;i<vA.length;i++) {
    for(var j=1;j<vA[i].length;j+=3) {
      if(vA[i][j] && vA[i][j+1] && vA[i][j+2]) {
        projArray.push([vA[i][0],vA[i][j],vA[i][j+1],vA[i][j+2]]);
        projObject.push({project:vA[i][0],person:vA[i][j],weight:vA[i][j+1],team:vA[i][j+2]}); 
      }
    }
  }
  var resultObj={array:projArray,object:projObject};
  var html='<style>td,th{border:1px solid black;text-align:center;}</style><table>';
  html+='<tr><th>Project</th><th>Person</th><th>Weight</th><th>Team</th></tr>';
  html+='<tr><td colspan="4">Array(indices)</tr>';
  for(var i=0;i<projArray.length;i++) {
    html+=Utilities.formatString('<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td>',projArray[i][0],projArray[i][1],projArray[i][2],projArray[i][3]);
  }
  html+='<tr><td colspan="4">Object(key,value)</tr>';
  for(var i=0;i<projObject.length;i++) {
    html+=Utilities.formatString('<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td>',projObject[i].project,projObject[i].person,projObject[i].weight,projObject[i].team);
  }
  html+='</table>';
  var userInterface=HtmlService.createHtmlOutput(html);
  SpreadsheetApp.getUi().showModelessDialog(userInterface, 'Array Assemble - Array on Top and Object on Bottom')
}

Answer №2

Do you have to create an entry for each team member row by row?

data = vA; 
for (var i=0; i<data.length;i++)
    {
    var project = data[i][0];
    if (data[i][1]!="")push([project,data[i][1],data[i][2],data[i][3] ]);//first person
    if (data[i][4]!="")push([project,data[i][4],data[i][5],data[i][6] ]);//second person
    if (data[i][7]!="")push([project,data[i][7],data[i][8],data[i][9] ]);//third person
    }//for loop

There might be a more graceful approach, but this is my initial idea.

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

Vue.js does not have the ability to toggle a font-awesome icon

I am having trouble toggling a font awesome icon based on a boolean value. It seems that the font-awesome icon stays on the screen even after it is drawn: Check out this link for reference HTML: <script src="https://unpkg.com/vue"></script> ...

unusual actions when decoding JSON data

For my current project, I am constructing a JSON object using JavaScript in the following manner: jsonArr.push({ position: 'WN', wind: windWN, wave: waveWN, sea: seaWN }); var myJs ...

What could be causing my Vue component to not refresh?

Can anyone help me figure out why this component isn't re-rendering after changing the value? I'm attempting to create a dynamic filter similar to Amazon using only checkboxes. Here are the 4 components I have: App.vue, test-filter.vue, filtersIn ...

What is the best way to determine the number of characters that will fit within the width of the document?

I am looking to create a JavaScript function using jQuery that can determine the number of characters that will fit in a single line within the browser window. While I am currently utilizing a monospace font for simplicity's sake, I would like to adap ...

Saving the ending reference to an array that has not been initialized within a compile-time context

I am currently working on designing a small buffer optimized vector type that is constexpr friendly. This vector type will have begin, end, and capacity pointers like a standard vector, but with a twist. When this vector is default constructed, the begin a ...

How can I retrieve information from an object using Mongoose queries?

Looking to retrieve data for all users with cardNumber: 3243 using the provided mongoose model. cred: { nameValue: 'anonymous', emailValue: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1879767776617 ...

Ways to trigger an onClick event multiple times in React

I have a code where I pass it to the onClick event and I want it to execute 3 times: (this code basically selects a random product from products and then updates the state using Hooks to display it in the shopping cart. Instead of just one product, I want ...

Enhance your website's functionality with the dynamic combination of Bootstrap

I am encountering an issue with the use of ui-router in combination with bootstrap collapse. <div class="panel panel-default" id="accordion" > <div role="tab" id="headingOne"> <a role="button" data-toggle="collapse" data-parent=" ...

Problem with Angular: ng-show not constantly re-evaluating expression

Utilizing a variable named activeScope to manage the state and toggle between two forms. This variable updates its value when a tab is clicked, triggering changeScope. While the change in active states for the tab buttons registers correctly, the divs for ...

The error message "Cannot call expressjs listen on socket.ip" indicates that there

Currently working on a project involving websockets, but encountering an error in the code below: TypeError: require(...).listen is not a function Here's what I have tried so far: const app = require("express")(); const port = 3800; const ...

(node:2824) UnhandledPromiseRejectionWarning: ReferenceError: The variable "role" has not been declared

I am currently in the process of getting my discord bot up and running again. The issue is that he is old, and in the previous version, this functionality worked. However, after reading other posts, I discovered that in order to make it work, I need to u ...

Change the color when hovering over the select box

Using jQuery, my goal is to change the hover color in a select box from its default blue to red. I understand that the hover color of the select input may vary based on the operating system rather than the browser, but I am making progress towards achievin ...

Slick Slider fails to load on web browsers

Hi everyone, I have a snippet of HTML code that I need help with: <!DOCTYPE html> <html> <head> <link rel="stylesheet" type="text/css" href="//cdn.jsdelivr.net/jquery.slick/1.6.0/slick.css"/> </head> <body> ...

Turn off the scrolling bars and only allow scrolling using the mouse wheel or touch scrolling

Is there a way to only enable scrolling through a webpage using the mouse wheel or touch scrolling on mobile devices, while disabling browser scroll bars? This would allow users to navigate up and down through div elements. Here is the concept: HTML: &l ...

How is it possible to retrieve a list of ID fields from an array of hash references in Perl?

What is the best way to extract each ID value from an array of hashes and push it into a new array in Perl? Consider the following array: @friends = [ {'id' => 1, 'last_name' => 'Fo', 'first_name' => & ...

javascriptDOM selectors document object

When selecting elements in my HTML page, I often find myself wondering why I always have to use the "document" keyword. For example: //variable body var content = document.getElementsByTagName("body"); Why can't I simply get all p tags from bo ...

Merge JavaScript function mouseup

I've been trying to combine JS functions, but it's not working as expected. Can anyone provide some suggestions for my code? $(document).ready(function(){ $(".searchs").keyup(function() { var searchbox = $(this).val(); var dataString = ...

What is the best way to retrieve a variable's value using its reference?

Within my array called tags are the names of various restaurants. I am attempting to utilize this information within a for loop in the GMapMarker to access data based on the restaurant name. let tags[] = {name: 'mcdonalds', id: '1'}, {n ...

AngularJS integration with Google OAuth

I'm working on integrating Google OAuth in AngularJS. Below is the code snippet for creating a Google sign-in button and the corresponding callback function. // Function for initializing Google sign-in <script type="text/javascript> a = f ...

I encountered a problem while trying to incorporate the solution that prompts another button click event

Interesting topic: JQuery / JavaScript - triggering button click event from another button <input type="submit" name="savebutton" id="uniqueOne" /> <input type="submit" name="savebutton" id="uniqueTwo" /> I have implemented a feature on my si ...