I have code where I'm trying to index and pull data from a previous sheet. This code used to work, but now i'm getting a typeError when running the code.
typeError
function updateLocations(market) { var activeSheet = SpreadsheetApp.getActiveSpreadsheet(); var lastPeriod = activeSheet.getSheetByName("Update Info").getRange("C7").getValue(); var sourceSheet = SpreadsheetApp.openByUrl(lastPeriod).getSheetByName("Assembly Redwood"); var targetSheet = activeSheet.getSheetByName("Assembly Redwood"); var targetArr = targetSheet.getRange(4,1,targetSheet.getLastRow(),10).getValues(); var sourceArr = sourceSheet.getRange(4,1,sourceSheet.getLastRow(),10).getValues(); var POlistTarget = targetArr.map(function(r){return [r[0],r[1]]}); var POlistSource = sourceArr.map(function(r){return [r[0],r[1]]}); var skuList = POlistTarget.map(function(r){return [r[1]]}); var arrSource = []; for(var i = 0; i < POlistSource.length; i++){ var POSKU = POlistSource[i][0]+POlistSource[i][1]; arrSource.push(POSKU); } var arrTarget = []; for(var i = 0; i < POlistTarget.length; i++){ var POSKU = POlistTarget[i][0]+POlistTarget[i][1]; arrTarget.push(POSKU); } var units = []; for(var i = 0; i < arrTarget.length; i++){ var row = arrSource.indexOf(arrTarget[i]); var unit = sourceArr[row][8]; //***************type error flags this line units.push([unit]); } Logger.log(units); }
All of the variables seem to be logging correctly, but I'm still getting the following error:
TypeError: Cannot read property '8' of undefined (line 333, file "Code")
Array.prototype.indexOf() returns the first index at which a given element can be found in the array, or -1 if it is not present.
Based on the error you are getting I assume that this returns -1:
-1
var row = arrSource.indexOf(arrTarget[i]) // value of row is -1
and therefore sourceArr[-1] undefined and these is why you can't use:
sourceArr[-1]
var unit = sourceArr[row][8]
because you are asking for the 8th element of something undefined sourceArr[-1].
Check first if you get a non-negative value from the indexOf method:
indexOf
var units = []; for(var i = 0; i < arrTarget.length; i++){ var row = arrSource.indexOf(arrTarget[i]); console.log(row) // console row to see its value if (row>-1){ var unit = sourceArr[row][8]; units.push([unit]); } }
or if (row!=-1) works as well.
if (row!=-1)
const sourceArr = [[3,1,4,30,32,12,1,4,5,3], [3,1,4,30,32,12,1,4,5,3], [3,1,4,30,32,12,1,4,5,3], [3,1,4,30,32,12,1,4,5,3]] console.log(sourceArr[0][8]); // this works console.log(sourceArr[-1][8]); // TypeError: Cannot read property '8' of undefined
2.1m questions
2.1m answers
60 comments
57.0k users