0

I missing something when trying to push to an array while preventing duplicates.

I keep figuring out code that will push every occurence of an employee to the new employees array but I cannot figure out how to only push an unique list.

My final array is a 2d array so that can be setValues() back into a column in the Google sheet.

function queryEmployees(){
  var sh = SpreadsheetApp.getActiveSpreadsheet().getSheets()[0];
  var lRow = sh.getLastRow();
  var data = sh.getRange(1,1,lRow,2).getValues();
  var employees = [];
  for(i=0;i<data.length;i++){
     if(data[i][0]==='Team member evaluated'){
       if(employees.indexOf([data[i][1]])===-1){
         employees.push([data[i][1]]);
       }
     }
  }
  Logger.log(employees);
  Logger.log(employees.length);
  SpreadsheetApp.getActiveSpreadsheet().getSheets()[1]
  .getRange(1,1,employees.length,1).setValues(employees);
    }
CRB
  • 71
  • 1
  • 6
  • Cheat! Use a [Set](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set). – Will Sep 25 '17 at 22:46
  • Avoid === for string comparisons and also ==. Use .equals() instead – Jeremy Kahan Sep 25 '17 at 22:47
  • Javascript doesn't have a .equals() method? == is the way to go. – James D Sep 26 '17 at 02:53
  • Thanks for the correction. I have been working in Java lately and forgot. I think == on the -1 might also help (at least worth a try) – Jeremy Kahan Sep 26 '17 at 03:57
  • I gave red herrings, sorry. The issue is that indexOf gets grumpy when looking for arrays, as opposed to strings. I think https://stackoverflow.com/questions/8668174/indexof-method-in-an-object-array is relevant. – Jeremy Kahan Sep 26 '17 at 04:32

1 Answers1

1

IndexOf does not work with objects in arrays without your rewriting the function or writing your own. It works fine with strings, though. So a simple fix is to create a parallel array of strings, which allows us to keep your code almost intact. Thus, add,

var employeesIndex=[];

after your

var employees=[]

change the condition on your inner "if" clause to

(employeesIndex.indexOf(data[i][1])===-1)

and within that if block add a line to update the index

employeesIndex.push(data[i][1]);

That way the index tracks duplicates for you while your employees array contains arrays like you need.

Jeremy Kahan
  • 3,796
  • 1
  • 10
  • 23