Как бороться с дубликатами в скрипте листов Google? - PullRequest
0 голосов
/ 04 февраля 2020

Так что в проекте, который я хочу сделать, у меня есть лист Google с временными метками и именами рядом с этими временными метками в электронной таблице. У меня проблемы с учётом дубликатов и присвоением имени нескольким временным меткам на другом листе Google.

for(var i = 0; i < length; i++){//for loop 1

if(currentCell.isBlank()){//current cell is blank
  daySheet.getRange(i+10, 2).setValue(fullName);//set name to first cell
  daySheet.getRange(i+10,3).setValue(pI);
  daySheet.getRange(i+10,day+3).setValue(1);    

}else if(counter > 1 ){//the index of the duplicate in the sheet month
      //if counter is > 1 then write duplicates
      for(var t = 1; t <= sheetLength ; t++){//loop through sign in sheet
          //current index i
          if(signInLN == signInSheet.getRange(t+1,3).getValue()){
          //if there is a match
            daySheet.getRange(t+10,day+3).setValue(1);
            //day is equal to the day I spliced from the timestamp

            //at this point I am confused on how to get the second date that has the same
            //name and add to the row with the original name.
            //when i splice the timestamp based on the row of index i, with duplicates I get 
            //the day number from the first instance where the name is read


          }
      }
}//for loop 1

Как мне заставить работать с дубликатами, чтобы я мог учитывать даты, но убедитесь, что если есть любые дубликаты будут добавлены в строку с оригинальным именем

Google Sheet EX:
12/10/2020   test1
12/11/202    test2
12/15/2020   test1 

Должно быть что-то вроде этого:

name       10   11   12   13   14   15   16
test1       1                        1
test2            1

// один должен идентифицировать, что дата - это когда пользователь вошел в систему на листах.

1 Ответ

0 голосов
/ 04 февраля 2020

Пример таблицы:

enter image description here


Фрагмент кода, созданный с помощью Apps Script , адаптируйте его под свои нужды.

используйте Logger.log(), если вы не понимаете части кода

Это делается в основном с функционалом JavaScript

function main(){
  var inputRange = "A2:B";
  var sheet = SpreadsheetApp.getActive().getSheets()[0]

  var input = sheet.getRange(inputRange).getValues(); //Read data into array

  var minDate, maxDate;
  var presentDates = input.map(function(row) {return row[0];}); //Turns input into an array of only the element 0 (the date)
  minDate = presentDates.reduce(function(a,b) { return a<b?a:b}); //For each value, if its the smallest: keep; otherwise: skip;
  maxDate = presentDates.reduce(function(a,b) { return a>b?a:b}); //Same as above, but largest.

  var dates = [];
  for (var currentDate = minDate; currentDate <= maxDate; currentDate.setDate(currentDate.getDate()+1)) {
    dates.push(getFormattedDate(currentDate)); //Insert each unique date from minDate to maxDate (to leave no gaps)
  }

  var uniqueNames = input.map(function(row) {return row[1];}) //Turns input into an array of only the element at 1 (the names)
                         .filter(function (value, index, self) {return self.indexOf(value) === index;}); //Removes duplicates from the array (Remove the element if the first appearence of it on the array is not the current element's index)

  var output = {}; //Temporary dictionary for easier counting later on.
  for (var i=0; i< dates.length; i++) {
    var dateKey = dates[i];
    for (var userIndex = 0; userIndex <= uniqueNames.length; userIndex++) {
      var mapKey = uniqueNames[userIndex]+dateKey; //Match each name with each date
      input.map(function(row) {return row[1]+getFormattedDate(row[0])}) //Translate input into name + date (for easier filtering)
      .filter(function (row) {return row === mapKey}) //Grab all instances where the same date as dateKey is present for the current name
      .forEach(function(row){output[mapKey] = (output[mapKey]||0) + 1;}); //Count them.
    }
  }

  var toInsert = []; //Array that will be outputted into sheets
  var firstLine  = ['names X Dates'].concat(dates); //Initialize with header (first element is hard-coded)
  toInsert.push(firstLine); //Insert header line into output.


  uniqueNames.forEach(function(name) {
    var newLine = [name];
    for (var i=0; i< dates.length; i++) { //For each name + date combination, insert the value from the output dictionary.
      var currentDate = dates[i];
      newLine.push(output[name+currentDate]||0);
    }
    toInsert.push(newLine); //Insert into the output.
  });

  sheet.getRange(1, 5, toInsert.length, toInsert[0].length).setValues(toInsert); //Write the output to the sheet
}

// Returns a date in the format MM/dd/YYYY
function getFormattedDate(date) {
  var year = date.getFullYear();

  var month = (1 + date.getMonth()).toString();
  month = month.length > 1 ? month : '0' + month;

  var day = date.getDate().toString();
  day = day.length > 1 ? day : '0' + day;

  return month + '/' + day + '/' + year;
}

Результаты выполнения скрипта: enter image description here

...