Find Cell Matching Value And Return Rownumber

后端 未结 4 502
名媛妹妹
名媛妹妹 2020-12-13 09:31

The employee sheet contains the name of the employee in cell C2. The name of the employee should also be on the data sheet in the range B3:B153.

How can I get the ro

4条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-13 09:58

    Since Google App Script is a JavaScript platform, I can think of two more methods to get the row index. It may be a bit faster because these are built-in Array methods.

    Method 1: using Array.prototype.forEach()

    function getRowIndexUsingforEach(){
      let term = 'user-1700@example.com';
      var data = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getRange(1, 1, 2000).getValues();
      data.forEach((val, index) => {
         if(val == term){
             Browser.msgBox(index+1); //because Logger.log() takes too long
         }               
      })
    }
    

    Method 2: using Array.prototype.findIndex()

    function getRowUsingfindIndex(){
      let term = 'user-1700@example.com';
      let data = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getRange(1, 1, 2000).getValues();
      let row = data.findIndex(users => {return users[0] == term});  
      Browser.msgBox(row+1); //because Logger.log() takes too long
    }
    

    To see which method will be faster, I ran these two methods and the accepted anwer's method over a column of 22000 rows of data several times. The averages are listed below:

    • Using for loop (from Accepted Answer): 2.66ms
    • Using Array.prototype.forEach: 11.75ms
    • Using Array.prototype.findIndex: 2.00ms

    I guess Array.prototype.forEach is not meant to find the index of a match; it is Array.prototype.findIndex that is designed for this purpose

提交回复
热议问题