While loop not stopping when 2D array cell isn't defined (javascript) - javascript

Goal: Run through the columns of a 2D array (comes from an Excel file with uneven column lengths) and put the entries that exist into their own array.
What I did: The length of the longest column is 90 entries, which is the second column in the Excel file, and the shortest is 30, which is the first column. I set up a for loop to go through each column and a while loop to go through each entry while it exists and append it to a new array.
Original(ish) Code:
//read in Excel file into 2D array called "myExcel"
var columnNames = ["shortest", "longest", "irrelevant"];
shortArray = [];
longArray = [];
irrArray = [];
var s
for (var i = 0; i < columnNames.length; i++) {
var columnName = columnNames[i];
s = 0;
while (myExcel[s][columnName]) {
if ((columnName === "shortest")) {
var row = myExcel[s][columnName];
shortArray.append(row);
s++;
} else if ((columnName === "longest")) {
var row = myExcel[s][columnName];
longArray.append(row);
s++;
} else if ((columnName === "irrelevant")) {
var row = myExcel[s][columnName];
irrArray.append(row);
s++;
}
}
}
Problem: It's only half working. It makes it through the first column (30 rows) just fine--it stops when myExcel[s][columnName] no longer exists (when columnName = "shortest" and after s = 29). Then, it makes it all the way through columnName = "longest" and s = 89 before giving me the error "TypeError: Cannot read property 'longest' of undefined". I'm assuming it's because it's trying to go through row 90, which doesn't exist. But I thought that's where my while loop would stop.
What I've Tried:
do while loop
//blah
do {
//blah
} while (myExcel[s][columnName]);
Added additional while loop condition
//blah
while ((myExcel[s][columnName]) && s<myExcel.length) {
//blah
}
Using typeof
//blah
while (typeof (myExcel[s][columnName]) === 'string') { //also used this with !=='undefined' and ==='string' when I added a number to the end of each row in the Excel sheet
//blah
}
And basically every combination of these (and probably much more I'm forgetting). I'm sure it's an easy fix, but I've spent days trying to figure it out so I guess I have to ask for help at this point. I'm also a MATLAB person and recently had to learn both Python and Javascript because of COVID, so it could possibly be a language switch issue (although I don't think so because I've been googling and messing with this for days). Any help would be very appreciated!

In your while loop change the check to,
while(myExcel[s] && myExcel[s][columnName] ) {
If you are writing modern Js, then you could simply optional chain it like so, while(myExcel[s]?.[columnName])
The thing is, you are trying to traverse inside an outer array. But you first need to check if outer array exists and then go check the inner array.

I don't fully understand you approach, but I think you're looking for this:
var shortArray = [];
var longArray = [];
var irrArray = [];
for(let row of myExcel){
if(!row) continue; // not sure if this check is necessary.
if(row.shortest) shortArray.append(row.shortest);
if(row.longest) longArray.append(row.longest);
if(row.irrelevant) irrArray.append(row.irrelevant);
}

Related

Apps Script JS adding items to array from range (if not already in array) fails

I am looping through various cells and want to add their string content do an array, if the content is not already in the array. It works perfectly fine when I do it manually like so, trying to add 'eJobs' to the array (see below "var item = 'eJobs') which already containts 'eJobs':
var divisionarray = ['eJobs']
for (var i = 0; i < cells_users.length-1; ++i) {
var row_users = cells_users[i];
if (row_users[0] == user_ldap) {
var podarray = row_users[1].split(', ')
for (j = 0; j < podarray.length; j++) {
for (var k = 0; k < cells_edit.length; ++k) {
var row_edit = cells_edit[k]
if (podarray[j] === row_edit[0]) {
var item = 'eJobs'
if (!(divisionarray.indexOf(item) >= 0)) {
divisionarray.push(item)
}
}
}
}
Logger.log(divisionarray)
As expected, the log file shows [17-10-08 19:11:04:111 BST] [eJobs], illustrating that the code works and 'eJobs' has not been added to the array as it is already in the array.
Now, when I change var item='eJobs' to values of a range
var item = sheet_pods_edit.getRange(startRow+k, startColumn+1).getValue();
the code does not work anylonger, as the log file shows:
[17-10-08 19:14:03:770 BST] [eJobs, eJobs, BestJobs, Vivre Deco, ...
Note I have a range of thousands of cells, so I get alot of duplicates added. What am I missing? Note the cells of the defined range are indeed just strings with a single word (e.g. 'eJobs').
The code is working and the log file is indicating what the problem is..
[eJobs, eJobs, BestJobs, Vivre Deco,
In the second eJobs there is a white space before eJobs, so the first value and the second value don't match.
Without seeing your data and going by the 'just strings with a single word' I would say that using a .replace(" ", "") on the text string should work, this will find the first " " in the string and remove it. I.e. " eJobs" would become "eJobs".
2.
Is this line of code just for testing? You should never use a method like this in a script. It will be extremely inefficient
var item = sheet_pods_edit.getRange(startRow+k, startColumn+1).getValue();
Instead get the full range using .getValues()and iterate over it then.
3.
Is there a reason you are using === in if (podarray[j] === row_edit[0]) unless you need to check for type always use ==

Google apps script - Broken for loop

I'm working in Google apps script and seem to have screwed up one of my for loops. I'm sure that I am missing something trivial here, but I can't seem to spot it.
Code Snippet:
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheets = ss.getSheets();
var lastRow = sheets[3].getLastRow();
var zw = sheets[3].getRange(2, 1, lastRow - 1, 26).getValues();
for (var j = 0; j < zw.length; ++j) {
if (zw[j][9] === 'Yes') {
var masterEmail = [];
var firstLetterLastName = [];
var first2Letter = [];
var masterEmail.push(zw[j][22]);
var firstLetterLastName.push(zw[j][1].charAt(0).toLowerCase());
var first2Letter.push(zw[j][1].charAt(0).toLowerCase() + zw[j][1].charAt(1).toLowerCase());
//The rest of the function follows...
}
}
What's Not Working:
The for loop doesn't increment. When running the code in a debugger, var j stays at a value of 0.0, and the rest of the function only runs based of off the values in the 0 position of zw.
What I need it to do (AKA - How I thought I had written it:)
The ZW variable is holding a 2 dimensional array of cell values from a Google sheet. I'm looping through that, checking the 9th value of each array entry for a string of "Yes" and then running the rest of the function (for each column with a "Yes") if the condition is true.
I thought I had this working before, but recently had to restructure and optimize some things. Now I'm starting to think I may need to rethink things and use a different loop method. Can anyone educate me?
Edit: Here's a bit more context as requested:
function menuItem1() {
var ui = SpreadsheetApp.getUi();
var response = ui.alert('Are you sure you want to send emails?', ui.ButtonSet.YES_NO);
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheets = ss.getSheets();
var lastRow = sheets[3].getLastRow();
var zw = sheets[3].getRange(2, 1, lastRow - 1, 26).getValues();
if (response === ui.Button.YES) {
for (var j = 0; j < zw.length; j++) {
if (zw[j][9] === 'Yes') {
var firstLetterLastName = [];
firstLetterLastName.push(zw[j][1].charAt(0).toLowerCase());
//Other Stuff....
}
}
}
}
I have a menu item attached to a simple onOpen, that calls menuItem1(). Calling the function prompts the user with a warning that they are about to send emails, then goes about getting data to assign email addresses based on the contents of the sheets. firstLetterLastName is an example.
I'm still not getting the loop to function, is it because I have it between two if statements? (Here is a link to the sheet)
Indeed it is quite trivial. You have mixed up your increment. You wrote
for (var j = 0; j < zw.length; ++j)
which means that you do 1 + i (and we know that at the start i = 0 which means your value will always be 1) instead of using the usual
for (var j = 0; j < zw.length; j++)
which would mean that you do i + 1 and update i, so you will get the expected 0 + 1 1 + 1 etc
EDIT:
First, I recommend instead of something like
if (responseMir === ui.Button.YES) {
// Your For loop
doing
if (responseMir !== ui.Button.YES) {
return
}
and in a similar fashion in the for loop
if (zw[j][9] !== 'Yes') {
break
}
It mostly helps increase readability by not including large blocks of code under a single if, when all you want to do is to stop execution.
Your for loop gets broken because of the mistake here:
teacherEmailMir.push(selValsMir[j][7]);
So your loop will go over once. However on the next itteration, you try to push selValsMir[1][7] which does not exist. Note that each itteration you have var selValsMir = []; inside the loop, which means that for every j selValsMir will always be an empty array. So with the following line
selValsMir.push([zw[j][0], zw[j][1], zw[j][2], zw[j][3], zw[j][4], zw[j][5], zw[j][7], zw[j][22], zw[j][23], zw[j][24]]);
your array will always have selValsMir.lenght = 1 and selValsMir[0].length = 10. So obviously trying to access anything from selValsMir[1] will throw you an error and stop the script right there.
I also recommend looking over the if statements that look at the first and first 2 letters of the name as I believe you can accomplish the same with less code. Always try to streamline. Consider using switch() where you end up using a lot of else if

Optimizing for loops in google apps script

I am using for loops to search through large sheets (approximately 4500 rows).
Most of them look something like this:
function lookup(value) {
var tables=SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Name");
var columnvalues = tables.getRange(1, 1,tables.getLastRow()).getValues();
var searchResult = columnvalues.findIndex(value); //Row Index - 1
}
Array.prototype.findIndex = function(search){
if(search == "") return false;
for (var i=0; i<this.length; i++)
if (this[i].toString().indexOf(search) > -1 ) return i;
return -1;
}
The app script currently runs relatively slowly. I am looking for a way to either speed up my current code or for another search method. I've been thinking about using the google spreadsheet lookup functions (index-match, vLookup) but I haven't found a way to access those functions in apps script. Any thoughts?
currently you wont find a way to do this faster with apps script. you have to get the entire column and search one by one like you are already doing.
the alternative you mention using sheet formulas can be flacky as you might find that the cell formulas dont inmediately update results as you change values.
the only case i can see this being sped up is if you need to make multiple search calls. in that case it will be faster to pass search terms as an array and search them all at once in the single loop.
As you are searching a single column something a bit simpler might be a bit faster.
function lookup(value) {
var searchResult = false;
if(value == "") return;
var tables=SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Name");
var columnvalues = tables.getRange(1, 1,tables.getLastRow()).getValues();
for (var i=0; i<columnvalues.length; i++) {
if(columnvalues[i][0] == value) {
searchResult = i; //Row Index - 1
break;
};
}
The fastest way that I have found of searching through an array is using the .filter() method of an array.
var yourData = range.getValues();
var results = yourData.filter(function(val) {
return val[0] == search ||
val[0].includes(search);
});
//now you have a 2d array of results
Modify that such that it is the range you want(sorry, on mobile) and that is the fastest way that I found. Avoiding the For-Loop is the best. You could also use a .forEach()

Can I select 2nd element of a 2 dimensional array by value of the first element in Javascript?

I have a JSON response like this:
var errorLog = "[[\"comp\",\"Please add company name!\"],
[\"zip\",\"Please add zip code!\"],
...
Which I'm deserializing like this:
var log = jQuery.parseJSON(errorLog);
Now I can access elements like this:
log[1][1] > "Please add company name"
Question:
If I have the first value comp, is there a way to directly get the 2nd value by doing:
log[comp][1]
without looping through the whole array.
Thanks for help!
No. Unless the 'value' of the first array (maybe I should say, the first dimension, or the first row), is also it's key. That is, unless it is something like this:
log = {
'comp': 'Please add a company name'
.
.
.
}
Now, log['comp'] or log.comp is legal.
There are two was to do this, but neither avoids a loop. The first is to loop through the array each time you access the items:
var val = '';
for (var i = 0; i < errorLog.length; i++) {
if (errorLog[i][0] === "comp") {
val = errorLog[i][1];
break;
}
}
The other would be to work your array into an object and access it with object notation.
var errors = {};
for (var i = 0; i < errorLog.length; i++) {
errors[errorLog[i][0]] = errorLog[i][1];
}
You could then access the relevant value with errors.comp.
If you're only looking once, the first option is probably better. If you may look more than once, it's probably best to use the second system since (a) you only need to do the loop once, which is more efficient, (b) you don't repeat yourself with the looping code, (c) it's immediately obvious what you're trying to do.
No matter what you are going to loop through the array somehow even it is obscured for you a bit by tools like jQuery.
You could create an object from the array as has been suggested like this:
var objLookup = function(arr, search) {
var o = {}, i, l, first, second;
for (i=0, l=arr.length; i<l; i++) {
first = arr[i][0]; // These variables are for convenience and readability.
second = arr[i][1]; // The function could be rewritten without them.
o[first] = second;
}
return o[search];
}
But the faster solution would be to just loop through the array and return the value as soon as it is found:
var indexLookup = function(arr, search){
var index = -1, i, l;
for (i = 0, l = arr.length; i<l; i++) {
if (arr[i][0] === search) return arr[i][1];
}
return undefined;
}
You could then just use these functions like this in your code so that you don't have to have the looping in the middle of all your code:
var log = [
["comp","Please add company name!"],
["zip","Please add zip code!"]
];
objLookup(log, "zip"); // Please add zip code!
indexLookup(log, "comp"); // Please add company name!
Here is a jsfiddle that shows these in use.
Have you looked at jQuery's grep or inArray method?
See this discussion
Are there any jquery features to query multi-dimensional arrays in a similar fashion to the DOM?

For loop exiting early while updating modified or new records in datatable.net table

I'm using the Datatables jQuery plugin. The table is pulling the data from an AJAX source (a SQL Server query, processed by ASP.NET into a JSON object). I want to create a live view of the table so that changes appear in real time. But rather than reloading the entire table every few seconds with fnReloadAjax() (which, from experience, has proven to be quite burdensome on the browser) I'm only updating the records that are new or modified, using fnAddData() and fnUpdate().
After getting a JSON object of just the new or modified records, here's my code to process the object.
var newData = updatedDataJSON.aaData;
if (newData[0] != null) {
for (i = 0; i < newData.length; i++) { //Loop through each object
if (newData[i].bNewCase === true) { //Process new cases
oTable.fnAddData(newData[i]);
} else { //Process modified cases
var tableArray = oTable.fnGetData();
var index;
var found = false;
var serial = newData[i].serial;
var dataObject = newData[i];
//First gotta find the index in the main table for
// the record that has been modified. This is done
// by matching the serial number of the newData
// object to the original aData set:
for (ii = 0; ii < tableArray.length; ii++) {
var value = tableArray[ii]['serial'];
value = value.replace(/<\/?[^>]+(>|$)/g, "");
if (value === serial) {
index = ii;
found = true;
}
}
if (found) {
oTable.fnUpdate(dataObject, index);
console.log('Updated ' + newData[i].serial);
}
}
}
}
My problem is that even though the newData.length property of the first for loop could be greater than 1, the for loop exits early (after one iteration). I added the console.log statement at the end and it started passing errors saying that newData[i].serial was undefined. This makes me think that the entire newData array was destroyed or something...
I'm really hoping that I've just made a stupid mistake (though I've checked and checked and checked some more but can't find one). Maybe there's something that I'm overlooking. If anyone has any advice, it would be greatly appreciated.
Credit goes to #elclarnrs for the solution, posted above in the comments. The solution was declaring the values of i and ii in the scope of the function. That got everything working smoothly. Good to know for future reference.

Categories