craftApprentice
craftApprentice

Reputation: 2777

How to fix Execution failed: TypeError: Can not read property "0" from undefined?

I have a sheet where some rows have pair values (in the first and in the 5th column) ​​that are always together (eg, identification person values​​) and values ​​that do not repeat (values related to some sort of event). I'm thinking about the most efficient way to automatically insert the second value when the user types the first value in the row. (the sheet contains thousands of lines and I wonder if it would be efficient). But when I run my code:

var columnPredicted = getColumnNrByName(activeSheet, 'MY_COLUMN')+1;
var activeCell = activeSheet.getActiveCell();
var activeRow = activeCell.getRow();
var givenValueCell = activeSheet.getRange(activeRow, 1);
var givenValue = activeCell.getValue();
var predictedCell = activeSheet.getRange(activeRow, columnPredicted);  
var lastRow = activeSheet.getLastRow()-1;
var input = activeSheet.getRange(2, 1, lastRow, columnPredicted).getValues();
Logger.log("input = " + input);
for(var j=input.length; j>0; j--){
     Logger.log("input = " + input[j][0]);          
        if (input[j][0] == givenValue) {
            predictedCell.setValue(input[i][0]);
            break;
        }

}

I got a message error saying that Execution failed: TypeError: Can not read property "0" from undefined. in the line Logger.log("input = " + input[j][0]). (the same happens in the line if (input[j][0] == givenValue) {. But the command Logger.log("input = " + input); shows the expected result. How to fix it?

Upvotes: 0

Views: 661

Answers (1)

Mogsdad
Mogsdad

Reputation: 45750

for(var j=input.length; j>0; j--){

An array will be [0..(length-1)], so there is no element [length]. Try this instead:

for(var j=input.length-1; j>0; j--){
                      ^^

Upvotes: 1

Related Questions