Convert the index match formula into a Google Script

I am currently consolidating tables from various sheets into one on Google Sheets. My goal is to create a function onedit(e) that can be paired with a loop function to execute this task.

=index($G$2:$G$8,match($A10&$I$1,arrayformula($B$2:$B$8&$E2:$E8),0),"").

As I am new to Google Script, I have been experimenting with formulas. However, the formula updates all adjacent cells, whereas I want it to match and remain static so that when column G is updated, the result is added to B10 without overwriting A10. (The cell I1 has the formula =today() for reference, but if the code can simply match with the date, that would be ideal!)

If you would like to see firsthand what I am referring to, here is the link to the sheet: https://docs.google.com/spreadsheets/d/1jviYYhI1V_bL8TMVvijR9vo_7sBFfktbhgblGNcYfrQ/edit?usp=sharing

The drop-down options in Column B2:B8 are linked to the list in A10:A18, just in case that makes a difference. Any assistance would be highly appreciated as I've been searching for a solution for three days now.

Answer №1

Check out this solution:

function autoload() {
  var ss = SpreadsheetApp.getActiveSheet();
  var meeting = ss.getRange("B2:F8").getValues();
  var targetNames = ss.getRange("A10:A18").getValues();
  var writtingRange = ss.getRange("B10:F18").getValues();
  var updatedUser = targetNames;
  var writtingColumn = -1;
  var coolMatrix;

  for (var i = 0; i < meeting.length; i++) {
    var name = meeting[i][0]
    for (var j = 0; j < targetNames.length; j++) {
      if (targetNames[j][0] == name) {
        for (var z = 0; z < writtingRange[0].length; z++) {
          if (writtingRange[j][z] == '' && writtingColumn < 0) {
            writtingColumn = z;
            break;
          }
        }
        writtingRange[j][writtingColumn] = meeting[i][4];
        updatedUser[j] = true;
      }
    }
  }

  whiteSpaceRemover(writtingRange);
  ss.getRange("B10:F18").setValues(writtingRange);
}

function whiteSpaceRemover(multidimensionalArray) {
  for (var i = 0; i < multidimensionalArray.length; i++) {
    for (var j = 0; j < multidimensionalArray[0].length; j++) {
      if (multidimensionalArray[i][j] == '') {
        multidimensionalArray[i].splice(j, 1);
        multidimensionalArray[i].push('');

      }
    }
  }

  for (var i = 0; i < multidimensionalArray.length; i++) {
    if (multidimensionalArray[i][0] == '') {
      for (var j = 0; j < multidimensionalArray[i].length; j++) {
        if (multidimensionalArray[i][j] != '') {
          whiteSpaceRemover(multidimensionalArray);
        }
      }
    }
  }

  return multidimensionalArray;
}

I tested this on a duplicate of your sheet and it successfully assigns the correct note next to the name and a '-' if they were absent from the meeting. It currently requires manual execution, but can be set up with an onEdit() trigger if needed.

Answer №2

function onEdit(event) 
    { var timezone = "GMT-5"; var timestamp_format = "MM/dd/yyyy"; // Timestamp Format. 
    var updateColName = "Student Name"; 
    var timeStampColName = "Date"; 
    var sheet, ss; 
    ss = SpreadsheetApp.getActiveSpreadsheet(); 
    sheet = ss.getActiveSheet();//Get the active sheet 
    var actRng = event.source.getActiveRange(); 
    var editColumn = actRng.getColumn(); 
    var index = actRng.getRowIndex();
    var headers = sheet.getRange(4, 1, 1, sheet.getLastColumn()).getValues(); 
    var dateCol = headers[0].indexOf(timeStampColName); 
    var updateCol = headers[0].indexOf(updateColName); 
    updateCol = updateCol+1; 
    if (dateCol > -1 && index >=5  && index <= 36 && editColumn == updateCol) { // only timestamp if 'Last Updated' header exists, but not in the header row itself! 
    var cell = sheet.getRange(index, dateCol + 1); 
    var date = Utilities.formatDate(new Date(), timezone, timestamp_format); cell.setValue(date); }

    function onEdit(){
        var ss = SpreadsheetApp.getActiveSheet();
        var meeting = ss.getRange("B2:F37").getValues(); 
        var targetNames = ss.getRange("A38:A90").getValues();
        var writtingRange = ss.getRange("B38:F90").getValues();
        var updatedUser = targetNames;
        var writtingColumn = -1;
        var coolMatrix;

        for(var i = 0; i < meeting.length; i++){ 
        var name = meeting[i][0] 
        for (var j = 0; j < targetNames.length; j++) { 
            if (targetNames[j][0] == name){
            for (var z = 0; z < writtingRange[0].length; z++) { 
                if (writtingRange[j][z] == '' && writtingColumn < 0) { 
                writtingColumn = z; 
                break; 
                }
            }
            writtingRange[j][writtingColumn] = meeting[i][4];
            updatedUser[j] = true; 
            }
        }
        }
        for (var w = 0; w < writtingRange.length; w++){
        if (writtingRange[w][writtingColumn] == ''){
            writtingRange[w][writtingColumn] = '-';
        }
        }
        ss.getRange("B38:F90").setValues(writtingRange);
    }}

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

The behavior of the select menu is erratic when interacting with AJAX

My dropdown menu is populated dynamically based on AJAX response: function populateDropdown(dropdownNum) { // invokeWebService using $.ajax json = invokeWebService("GET", "/webservice/dropwdownOptions"); optionsHtml = ""; $.each(json, function(count, jsO ...

Trigger an analytics event from a background chrome extension

I've encountered a challenge with sending an event to Google Analytics from background.js, which is the background script of my Chrome extension. This is the code snippet I added to my background.js file: var _gaq = _gaq || []; _gaq.push(['_set ...

What is the sequence in which Jest executes its tests?

A fascinating challenge I've taken on involves testing a card game created in JavaScript using Jest. Currently, I have developed two tests: one to verify the creation of a 52-card deck and another to confirm that the player is dealt two cards at the ...

The comparison between importing TypeScript and ES2015 modules

I am currently facing an issue with TypeScript not recognizing the "default export" of react. Previously, in my JavaScript files, I used: import React from 'react'; import ReactDOM from 'react-dom'; However, in TypeScript, I found tha ...

Transmit the identification to angularjs for the genuine content to be displayed

I have a hidden field where I store an Id, which can also be 2, 3, 4, or 59. I need to send this Id from the hidden field to my opgaver.js file so it can download the content. However, I am facing difficulty in figuring out how to pass the Id to the opgav ...

creating dynamic column headers with JavaScript

I am looking for a way to make the column names dynamic so that I don't have to manually update them every time. Here is my code snippet: jqGrid11.prototype = { display : function() { $('body').append(this.html.join("")); $("#jqGrid").j ...

Can one use Javascript to access the Sharepoint REST API from an external source?

I'm looking to showcase the content of a Sharepoint list on an external webpage. I'm interested in using Javascript or PHP to make a REST call to Sharepoint for this purpose. Although I've researched Sharepoint's REST API, I'm uns ...

The problem with THREE JS OcclusionComposer: encountering "Cannot read properties of undefined (reading 'x')" error

I am attempting to replicate the Volumetric Lighting demonstration created by JMSWRNR but I am encountering difficulties with the Occlusion Composer. Since I am not well-versed in GLSL, debugging has proven to be quite challenging, especially for someone l ...

Converting a string into a TypeScript class identifier

Currently, I am dynamically generating typescript code and facing an issue with quotes in my output: let data = { path: 'home', component: '${homeComponentName}', children:[] }; let homeComponentName = 'HomeComponent' ...

Ensuring the accuracy of nested objects through class validator in combination with nestjs

I'm currently facing an issue with validating nested objects using class-validator and NestJS. I attempted to follow this thread, where I utilized the @Type decorator from class-transform but unfortunately, it did not work as expected. Here is my setu ...

Transmit the document to Django using Ajax

I am encountering an issue when trying to send an image using an AJAX request to Django. Below is the HTML code I am using: <form> <input type="file" id="files" name="image"> </form> Next, here is the corresponding JavaScript code: var ...

How to maintain row highlight in jQuery datatable even after it is reloaded

I have a datatable set to reload every 10 seconds. When a user clicks on a row, it highlights, but the highlight is lost when the table reloads. Here is a condensed version of my datatable code: $(document).ready(function() { // set up datatable $(& ...

The functionality of Jquery Ajax is functioning seamlessly on my local machine, but encountering issues

HTML Code $('#btnTariefVerwijderen').click(function () { if (TariefId != undefined && TariefId != "" && TariefId != null) { if (window.confirm("Weet u zeker dat u de gesselecteerde rij(en) wil ...

What could be causing the triggering of two AJAX requests in the given JavaScript code?

I have a code snippet that fetches data from the server. I want to trigger it on document.ready(). My expectation is that the first request is sent to the server, receives a response, and then the second request is made, and so forth. However, when I insp ...

Guidelines on integrating Admob into Ionic framework

I tried following the steps outlined in this post: AdMob not loading ads in ionic/angular app After running the app using "ionic build ios && ionic emulate ios," I still see no ads, no black bar, nothing at all. Can someone help me figure out wha ...

Is it feasible to maintain the color of an element after clicking a button with the use of arrays?

Is it possible to make a button retain its hover color even after it has been clicked using a php/ejs script? The script is running on Ajax, so the page does not refresh. I have managed to get the color retention feature to work, but it always defaults to ...

Add JSON elements to an array

Looking for help! {"Task": [Hours per Day],"Work": [11],"Eat": [6],"Commute": [4],"Sleep": [3]} Need to add these items to a jQuery array. I've attempted using JSON.parse without success. Typically, I can push parameters as follows: MyArr.push([& ...

Displaying HTML content using Typescript

As a newcomer to typescript, I have a question regarding displaying HTML using typescript. Below is the HTML code snippet: <div itemprop="copy-paste-block"> <ul> <li><span style="font-size:11pt;"><span style="font-family ...

Retrieve the value of a property in a JavaScript object by specifying a dynamic key for the property

As I work on my current project, I find myself immersed in a world of SVG animations. The challenge lies in triggering these animations as the user scrolls down to view the SVGs. To address this, I took the approach of creating functions for each Snap.SVG ...

``Error: GraphQL server unable to initiate due to a failure in the module.exports

While learning GraphQL, I encountered an error when attempting to start a server. const graphql = require('graphql'); const _ = require('lodash'); const { GraphQLObjectType, GraphQLString, GraphQLInt, GraphQLSchema } ...