Delete outdated information using Google Apps Scripts when the date is less than the current date plus a specified number of days

I have a Google Sheet where I need to filter out entries based on the number of days since the last check. Specifically, I want to keep only those entries where the number of days since the last check is greater than 10.

You can find the Sheet here.

function check(){

/** Setting Variables **/ 
  var ss = SpreadsheetApp.getActiveSpreadsheet(); 
  var sh1 = ss.getSheetByName('Data Processing');

/** Removing Duplicates **/ 
  var sh1data = sh1.getDataRange().getValues(); 
  var sh1newData = []; 
  for (var i in sh1data) { 
    var row = sh1data[i]; 
    var duplicate = false; 
    for (var j in sh1newData) {
/* Checking Date */
      var today=new Date().valueOf(); 
      var sec=1000;  
      var min=60*sec;  
      var hour=60*min;  
      var day=24*hour; // Convert time units
      var sh1DateChecked = sh1newData[j][4].valueOf(); 
      var diff=today-sh1DateChecked; 
      var days=Math.floor(diff/day); // Calculate Days since last check
      
if(row[0] == sh1newData[j][0] && row[1] == sh1newData[j][1] && days > 10)
{ duplicate = true; } } 
    if (!duplicate) { sh1newData.push(row);
                     
} 
  } 
  sh1.clearContents();
  sh1.getRange(1, 1, sh1newData.length, sh1newData[0].length).setValues(sh1newData); 

}

Answer №1

In solving the problem at hand, the focus is on removing dates less than 10 days old rather than dealing with duplicates as mentioned in the code. However, adding functionality to remove duplicates can easily be incorporated if needed.

A suggestion is to encapsulate the condition within a function that takes a row of data as input and outputs a boolean value, like so:

function dateCheckedOlderThan10Days(row) {
  return getDays(row[4]) > 10;
}

function getDays(date) {
  const sec = 1000;
  const min = 60 * sec;
  const hour = 60 * min;
  const day = 24 * hour;  
  return Math.floor((new Date() - date)/day);  
}

(Notice how the getDays function can be extracted out from the main function for better code organization.)

This function seamlessly integrates into Array.prototype.filter, providing clarity on the expected behavior through its naming.

const dataOlderThan10Days = ss.getSheetByName('Data Processing')
  .getDataRange()
  .getValues()
  .filter(dateCheckedOlderThan10Days);

The refactored checked function broken down into smaller functions:

Code.js

function check() {
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const dataSheet = ss.getSheetByName('Data Processing');
  const data = dataSheet.getDataRange().getValues();
  const dataOlderThan10Days = data
    .slice(1) // excludes header row; adjust according to presence of headers
    .filter(dateCheckedOlderThan10Days);
  dataSheet.clearContents();
  //dataOlderThan10Days.unshift(data[0]); // <-- include if restoring headers is needed
  setData(dataSheet, dataOlderThan10Days);
}

function dateCheckedOlderThan10Days(row) {
  return getDays(row[HEADINGS.DATE_CHECKED]) > 10;
}

const HEADINGS = {
  FIRST_NAME: 0,
  LAST_NAME: 1,
  SALARY: 2,
  AGE: 3,
  DATE_CHECKED: 4
};

function setData(sheet, data) {
  sheet.getRange(1, 1, data.length, data[0].length).setValues(data);
}

function getDays(date) {
  const sec = 1000;
  const min = 60 * sec;
  const hour = 60 * min;
  const day = 24 * hour;  
  return Math.floor((new Date() - date)/day);  
}

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

Attempting to call a nested div class in JavaScript, but experiencing issues with the updated code when implemented in

Seeking assistance. In the process of creating a nested div inside body > div > div . You can find more information in this Stack Overflow thread. Check out my JSFiddle demo here: https://jsfiddle.net/41w8gjec/6/. You can also view the nested div on the ...

Unable to load circles on page refresh with amCharts Maps

I am experiencing an issue with the functionality of my amCharts maps. Whenever I refresh the page, the circles that are supposed to be displayed disappear. However, when I zoom in, the circles reappear. This problem has me puzzled, and I'm not sure ...

What is the best way to ensure that consecutive if blocks are executed in sequence?

I need to run two if blocks consecutively in TypeScript, with the second block depending on a flag set by the first block. The code below illustrates my scenario: export class Component { condition1: boolean; constructor(private confirmationServic ...

Alternative for Jquery: a new Hash Table solution using Prototype JS

Greetings everyone! I have experience as a prototype JS developer but now I am transitioning to jQuery for work/client reasons. One feature I really liked in Prototype was the Hash class, such as var h = new Hash();. However, I understand that jQuery doe ...

Uncovering the hidden gems within a data attribute

Trying my best to explain this clearly. What I have is a data-attribute that holds a large amount of data. In this case, I need to extract each individual basket product ID and display them as separate strings. The challenging part for me is locating thi ...

What could be causing the data in the data table to remain undeleted unless the page is manually refreshed

I am facing an issue with the delete button functionality. When I press the button, it successfully deletes the row but requires a page refresh to make the deleted row disappear. How can I resolve this problem and ensure that the row is deleted without the ...

MUI: Autocomplete received an invalid value. None of the options correspond to the value of `0`

Currently, I am utilizing the MUI autocomplete feature in conjunction with react-hook-form. I have meticulously followed the guidance provided in this insightful response. ControlledAutoComplete.jsx import { Autocomplete, TextField } from "@mui/mater ...

The Ajax function is unable to accept JSON data as input

I am trying to figure out why I am unable to access data from a JSON object (json.projects[i].projName) when calling it from within an AJAX function. Below is the code that demonstrates this issue: var json = JSON.parse(data); for (var i = 0; i < json ...

Converting an object of objects into an associative array using Javascript and JSON

Using AngularJS, I am sending this data to my API : $http.post('/api/test', { credits: { value:"100", action:"test" } }); Upon receiving the data in my nodeJS (+Express) backend, it appears as follows : https://i.stack.imgur.com/NurHp.png Why ...

Visual Studio Code encounters a JavaScript NPM error that is causing unexpected issues

When using Visual Studio Code, I want my JavaScript program to automatically run through a server as I am learning online. I followed the steps from a tutorial on setting up my IDE and installed Git and Node. Now, when I open Visual Studio and save my Hel ...

Is there anything else I should attempt in order to fix this npm start error?

I have been troubleshooting this issue by researching other stack overflow posts, but I continue to encounter the same error message repeatedly. My goal is to execute a Javascript program that incorporates ReactJS. Initially, everything was functioning sm ...

When using the e.target.getAttribute() method in React, custom attributes may not be successfully retrieved

I am struggling with handling custom attributes in my changeHandler function. Unfortunately, React does not seem to acknowledge the custom "data-index" attribute. All other standard attributes (such as name, label, etc.) work fine. What could be the issu ...

Tips for refreshing an html table without affecting the scroll location?

HTML: <div class="html_table"></div> # Within the html body tag. Utilizing Ajax function to retrieve table data. var $html_table= $('.html_table'); function ajaxCallFunction() { $.ajax({ type: 'POST', ...

What is the best method for deleting a portion of a string following the final instance of a particular character?

I have a single string that looks like this: "Opportunity >> Source = Email >> Status = New >> Branch = Mumbai" My goal is to truncate the string from the last occurrence of >>. Essentially, I want the resulting string to be: "Op ...

Leveraging JavaScript to create a horizontal divider

Just a quick question - how can I create a horizontal line in Javascript that has the same customization options as the HTML <hr> tag? I need to be able to specify the color and thickness of the line. I am working on a website where I have to includ ...

Using JavaScript to dynamically alter the background image of an HTML document from a selection of filenames

Just starting out with JavaScript and working on a simple project. My goal is to have the background image of an HTML document change to a random picture from a directory named 'Background' every time the page is opened. function main() { // ...

searchByTextContentUnderListItemAnchorTag

I would like to utilize the getByRole function for writing my test. However, I am encountering issues when using linkitem or 'link' as the role. It seems that I cannot find the desired element. // encountered error TestingLibraryElementError: The ...

Issues with React Native imports not functioning properly following recent upgrade

Hey there, I’ve been tasked with updating an old React-Native iOS project from version 0.25.1 to 0.48.0. However, I’m encountering several compiler issues and struggling to navigate through the code updates. The project includes an index.ios.js file s ...

What makes using the `@input` decorator more advantageous compared to the usage of `inputs:[]`

In defining an input on a component, there are two available methods: @Component({ inputs: ['displayEntriesCount'], ... }) export class MyTable implements OnInit { displayEntriesCount: number; Alternatively, it can be done like this ...

Organize the array by property name and include a tally for each group

My current data structure looks like this: var data = [ { MainHeader: Header1, SubHeader: 'one'}, { MainHeader: Header1, SubHeader: 'two'}, { MainHeader: Header2, SubHeader: 'three'}, { MainHeader: Header2, SubHea ...