'Add new records to "database" and update existing records that have a change. How to add data to the correct rows?

I've been piecing together a script that will take a row of data from all spreadsheets in my drive that contain X in the file name and were updated within the last day, and add that row to a primary "database" spreadsheet. Everything works great. The issue I have is that I'd like to add two columns to each row that is being added or updated to record the original sheet url and the current date/time.

I'm already able to access both the url value (urls for all or url for each) as well as the date/time (now), but I can't figure out where in my script to add them so they appear in my final output.

Below is the current code. How can I resolve this?

  var urls = [];
  var originalSheetName = 'sheetNameToCopy';
  var now = new Date();
  var yesterday = new Date();
  yesterday.setDate(yesterday.getDate() - 1);
  var yesterday = yesterday.toISOString().substring(0, 10);
  var files = DriveApp.searchFiles('modifiedDate > "'+yesterday+'" and mimeType = "application/vnd.google-apps.spreadsheet" and title contains "X"'); 
  while (files.hasNext()) {
    var file = files.next();
    urls.push([file.getUrl()]);
    } 

  for(var i = 0; i < urls.length; ++i){
      var originalSpreadsheet = SpreadsheetApp.openByUrl(urls[i][0]);
      var targetSheet = SpreadsheetApp.openByUrl('ADD TARGET SHEET URL HERE').getSheetByName('Summary'); //ADD TARGET SHEET URL
      
  const OFFSET = 1;
  const data = targetSheet.getRange(1 + OFFSET, 1, targetSheet.getLastRow() - OFFSET, 20).getValues();
  var url = urls[i];
  const values = originalSpreadsheet.getSheetByName(originalSheetName).getRange('A3:T3').getValues().filter(row => {
      if (row[0] === '') return false;
      const index = data.findIndex(r => r[0] === row[0]);
      if (index === -1) return true;
      data[index] = row.slice();
      return false;
    });
    
    targetSheet.getRange(2, 1, data.length + values.length, data[0].length).setValues(data.concat(values));
  }
}


Solution 1:[1]

You can use unshift or push and add those two columns in front or back of the values array:

It will look like this :-

values.forEach(r=>r.unshift(now , url )) // will add Date and Url at Front

or

values.forEach(r=>r.push(now , url )) // will add Date and Url at back

Use any of the approach mentioned above before you're setting values, like this:-

values.forEach(r=>r.unshift(now , url ))
targetSheet.getRange(2, 1, data.length + values.length, data[0].length).setValues(data.concat(values));

Reference:

unshift

push

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 vector