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);
    }
5
  • Cheat! Use a Set. Commented Sep 25, 2017 at 22:46
  • Avoid === for string comparisons and also ==. Use .equals() instead Commented Sep 25, 2017 at 22:47
  • Javascript doesn't have a .equals() method? == is the way to go. Commented Sep 26, 2017 at 2: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) Commented Sep 26, 2017 at 3:57
  • I gave red herrings, sorry. The issue is that indexOf gets grumpy when looking for arrays, as opposed to strings. I think stackoverflow.com/questions/8668174/… is relevant. Commented Sep 26, 2017 at 4:32

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Very helpful, great idea @Jeremy

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.