Please add a new row following the date that falls on a Sunday using Google Apps Script

I have a dataset in my google sheets where one of the columns contains various dates. My objective is to add an empty row under every date that falls on a Sunday (regardless of the year). I am only concerned with identifying the day of the week.

I have come up with a pseudo-code outline for this task:

  1. Iterate through the column containing dates
  2. Modify the date format to display only the full abbreviation of the day (e.g., Sunday)
  3. If the formatted day is "Sunday", then insert a new row below that specific date.

Below is the current script I am using:

function addRows() {
  const ss = SpreadsheetApp.getActiveSpreadsheet()
  const sheet = ss.getActiveSheet();
  const range = sheet.getDataRange();
  const data = range.getValues();

  for (let i = 1; i < data.length; i++) {
    const sheetDate = data[i][0];
    const day = Utilities.formatDate(sheetDate, ss.getSpreadsheetTimeZone(), "EEEE");
    if (day === "Sunday") {
      sheet.insertRowsAfter(i, 1); // However, I suspect the issue lies within this line as it should not be i but rather the index of the row containing the value "Sunday"
    }
  }
}

I seem to be encountering some confusion regarding the first argument of the insertRowsAfter() function. What value should this argument actually represent?

Answer №1

One interesting observation is that whenever new rows are inserted after a certain row position, the data range automatically adjusts, necessitating an adjustment in the row position for subsequent rows containing the day Sunday.

Recommendation

You might want to consider implementing the modified script provided below:

function addRows() {
  const ss = SpreadsheetApp.getActiveSpreadsheet()
  const sheet = ss.getActiveSheet();
  const range = sheet.getDataRange();
  const data = range.getValues();
  var count = 0;

  for (let i = 1; i < data.length; i++) {
    var row = i+1;
    const sheetDate = data[i][0];
    const day = Utilities.formatDate(sheetDate, ss.getSpreadsheetTimeZone(), "EEEE");
    if (day == "Sunday") {
      count += 1;
      var curRow = row+count;
      curRow -= 1;
      sheet.insertRowsAfter(curRow,1)
    }
  }
}

Example Test

  • Test Sheet:

https://i.sstatic.net/nUerk.png

  • Result after executing the modified script:

https://i.sstatic.net/0Dzni.png

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

What is the best way to send a POST request to a certain URL using Axios in a React application?

I am facing a challenge with making a post request to a rather complex URL: http://localhost:8080/api/login?email=example%40gmail.com&password=examplepassword as per the Swagger-UI documentation. The examples on axios's GitHub page mention that th ...

CSS - Discovering the reason behind the movement of text post generation (animation)

I have a question regarding CSS animation, specifically the typewriting effect. I was able to successfully achieve the typewriting effect using animation. However, I noticed that even though I did not set any animation for transforming, once the text is g ...

Automatically adjust the size of the iframe when the content within it changes

The Iframe on another domain uses Ajax internally, causing its height to change when different dropdown values are selected. Check out the demo of the Iframe [here](http://jsfiddle.net/pq7twrh2/5/) As I select various dropdown options within the Iframe, ...

Maximizing Server Performance with Query Data Caching

I am currently developing an Express app that involves transferring data from views to a database. However, the majority of the data needs to be linked to other data within different tables in the database. For instance, there is a "choose student name" d ...

Having trouble accessing ms-appdata:///local directory after capturing a photo

Having an issue with my Cordova application designed for Windows 8.1, I am trying to capture a photo and display it on the screen while also saving it in the local folder. Within one of my directives, I have the following function: scope.takePhoto = func ...

Having difficulty accessing $scope beyond the function

One of the functions in my code is called getMail() $scope.getMail=function(){ $http.get(APISource). success(function(data) { $scope.mail =data; }). error(function(data) { console.log("error"); console.log(data); }); } In the succe ...

To ensure that the first three digits of a phone number are not zeros, you can implement a JavaScript function to validate the input

I've been working on validating a phone number using JavaScript, but I've hit a roadblock. I need to ensure that the area code (first 3 numbers in 999) cannot be all zeros (0). While I know how to create the desired format (like xxx-xxx-xxxx), ...

Tips for displaying JSON data by formatting it into separate div elements for the result object

Having recently started using the Amadeus REST API, I've been making AJAX calls to retrieve data. However, I'm facing a challenge when it comes to representing this data in a specific format and looping through it effectively. function showdataf ...

How can I apply a texture to a 3D rectangle in THREE.js?

I am attempting to create a 3D box in THREE.js that represents a box made up of 2x4 Legos, measuring 24 pieces wide by 48 pieces long and an unspecified number of pieces tall. I have created a texture displaying this pattern using random colors: https://i ...

Issue with displaying image element over another element

I recently encountered a unique challenge with my SVG element, which acts as a container for a chessboard I developed. In certain key moments of the game, such as when a pawn is promoted and a player needs to choose a new piece, I found it necessary to hav ...

Why is the function app.get('/') not triggering? The problem seems to be related to cookies and user authentication

Need help with app.get('/') not being called I am working on implementing cookies to allow multiple users to be logged in simultaneously. Currently, users can log in successfully. However, upon refreshing the page, all users get logged in as the ...

Transforming jQuery into classic JavaScript traditions

I want to convert the code below into pure JavaScript. document.addEventListener('click', function(event) { if (event.target.classList.contains('savedPlayer')) { event.preventDefault(); let searchText = event.target.textCon ...

Is there a way to retrieve JSON data from a specific URL and assign it to a constant variable in a React application?

I am exploring react-table and still getting the hang of using react. Currently, in the provided code snippet, a local JSON file (MOCK_DATA.json) is being passed into the const data. I want to swap out the local JSON with data fetched from a URL. How can ...

How to create buttons in React to increase and decrease a value?

Just starting out with React and attempting to create a ticket counter. The goal is to increase or decrease by 1 based on the direction of the arrow clicked. However, I'm facing an issue where nothing is displaying on my webpage. Any ideas on what mig ...

Using Vue: Dynamically pass components to router-view within dynamically loaded components

For a specific URI, I am looking to display a different layout on the same route by using different components based on whether the user is on mobile or desktop. I want to avoid cluttering the PageCommon (layout component) with route path checks. In the a ...

An unexpected error occurred while attempting to establish a connection to a MySQL server using Sequelize: 'LRU is not a constructor'

I have been working on a web application that utilizes boardgame.io's Tic-Tac-Toe tutorial game, with a twist - the results of each match are saved to a MySQL database. The current state of my code involves trying to establish a connection to the data ...

Is there a way to directly save a JSON object into the DOM?

Is there a way to store the output of a JSON.parse as a single entity in the DOM? For example: jsonObject = JSON.parse(something); I am interested in finding a method to store the jsonObject in the DOM, such as a child element or textNode, so that I can ...

Errors have been observed when using JavaScript variables that begin with the symbol $

For the longest time, I've used JavaScript variable names that begin with $ to signify that they hold jQuery values. For example: $buttons = $( 'button' ); However, a couple of nights ago, I encountered an issue when loading the page in the ...

Access to an Express route in Node JS can only be granted upon clicking a button

Is it feasible to create an express route that can only be accessed once a button is clicked? I want to prevent users from entering the route directly in the URL bar, and instead require them to click a specific button first. I'm curious if this can b ...

Can anyone identify the result produced by this line of code? Utilizing the $.get method to access "http://192.168.4.1:80/" with the parameter {pin:p}

Can anyone explain the output of this line of code? $.get("http://192.168.4.1:80/", {pin:p}); I understand that it is an Ajax code that sends data through a GET request, but I am trying to manually send the same data like this ".../pin:13" or "", however ...