简体   繁体   中英

How do I count the number of rows in an array?

My task is to grab a 2-dimensional table from cells on a worksheet into a 2-dimensional array, delete some or all of the rows (right terminology?) from testing, and then paste what's left into a worksheet.

To determine the range for pasting I need to know the length of the edited array. This is where I'm challenged.

// This gets the array which is 3 columns wide and X rows (X will vary)
  var termEmp = spreadsheet.getRangeByName("roeList").getValues();  
// e.g. termEmp = [ ["Bob", 1, "day", "key"] ["Cindy", 2, "day", "it"] ["Laura", 1, "night", "we"] ]

// Then I find the number of rows that actually have data 
numRows = termEmp[0].length;             // result = 3

// A for loop with counter i tests if the second element equals 2 of each row and deletes each array row if it's there
// In this example I want to delete the row with Cindy because of the 2
// To do this is use the splice method to delete the second row thusly:
termEmp.splice(i,1);                    // i = 1 in the for loop

// After testing all elements, and deleting the rows I want, I then need to count the number of rows remaining (to create a range for pasting into the worksheet)
numRows = termEmp[0].length;            
// This is SUPPOSED to count the number of rows remaining (first element is ALWAYS non-blank)

Here's my problem. For this example the number of rows after the splice goes from 3 to 2. I looked at the array to confirm this.

But in my code termEmp[0].length STAYS at 3. I can't use it to define my range for pasting.

What's needed to get the count right?

For number of rows, you can get the length of the full array.

 var numRows = termEmp.length

What you're getting with termEmp[0].length is the number of columns in first row.

EDIT OP indicated the answer "doesn't work" (which is false) however, as a courtesy here's subsequent code that helps his followup question to identify members in an array contain another array (effectively 2-dimensional spreadsheet data). The below code will take all memembers from termEmp that are an array, and inserts them into cleanedArray .

var cleanedArray = [];
for(var i=0;i<termEmp.length;i++){
  var singleMember = termEmp[i];
  if(Array.isArray(singleMember)){
    //makes a clean array with only 2d values
    cleanedArray.push(singleMember);
  }
}
var numberOfMembers = cleanedArray.length;
Logger.log(numberOfMembers);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM