Search code examples
arraysgoogle-apps-scriptconditional-statementscopy-paste

Copy value if it exists in Table 1 but not in Table 2


So essentially I have two tables. Table 1 has a list of all attendants to a certain event. Table 2 has a list of all members of an organization that attended said event. I'm trying to copy a list of all non-members that attended the event. So the logic in my head is trying to loop through Table 2 and see if the value also exists in Table 1. If it does not, I'm trying to copy it into a list.

    var attendants = currentS.getRange("M2:M").getValues(); //this is the list of all members that attended an event
       for (var x = 2; x <= checkLast; x++) {
          newcheck = currentS.getRange(x,5).getValue(); //this is getting the name of the attendants
       if (attendants.indexOf(newcheck) == -1) {
             var columnM = currentS.getRange("M1:M").getValues(); //trying to see if name of attendants is in the list of all members that attended the event. 
             var columnMlast = columnM.filter(String).length;
             var final = currentS.getRange(columnMlast+1,13);
    
             final.setValue(currentS.getRange(x,5).getValue()); //if it attendant is not in the list of members that attended, copies the name into a new list. 

Whenever I run the code, I end up just getting the whole list of attendants without anything being filtered out. I hope I'm clear, and thanks in advance!!


Solution

  • Explanation:

    You can use the filter method to find the items of attendants that are not included in the list of members and that will result in the list of new_members that will be appended at the bottom of members.

    Using this solution you don't need for loops and most importantly you don't need to use setValue and getValue in a loop which is computationally expensive.

    Solution:

    I can't use your code because you have variables that aren't defined in the code snippet you provided.

    I will show you an example (sheet and code) that you can use to adjust your current solution.

    Example Script:

    function myFunction() {
      const ss = SpreadsheetApp.getActive();
      const currentS = ss.getSheetByName("Sheet1");
      const members = currentS.getRange("M2:M").getValues().flat().filter(r=>r!='');
      const attendants = currentS.getRange("N2:N").getValues().flat().filter(r=>r!='');
      const new_members = attendants.filter(a=>!members.includes(a)).map(nm=>[nm]);
      console.log(new_members) // output: [ [ 'guest1' ], [ 'guest2' ], [ 'guest3' ], [ 'guest4' ] ]
      currentS.getRange(members.length+2,13,new_members.length,1).setValues(new_members);
    }
    

    Example sheet (Input-Output):

    enter image description here