Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I store a range of cells to an array?

If I have a list of data in cells A1:A150 (but the amount can vary), is there a way to push that into an array without looking at each cell individually to determine if it is empty? I exceed my execution time by doing this and I need a faster way to store the data and stop when it hits an empty cell.

Below is how I currently do it:

for (var i = 1; i < 500; i++) {
  if(datasheet.getRange("A" + i).getValue() == ""){
   break;   
  }

  else{
     addedlist_old.push(datasheet.getRange("A" + i).getValue())
    }
like image 638
Aaron Avatar asked Nov 29 '22 13:11

Aaron


1 Answers

If you're using only one column, I'd suggest:

  // my2DArrayFromRng = sh.getRange("A2:A10").getValues();
  var my2DArrayFromRng = [["A2"],["A3"],["A4"],["A5"],[],[],["A8"],["A9"],[]];
  var a = my2DArrayFromRng.join().split(',').filter(Boolean);

The methods .join() and .split(',') together convert the 2D array to a plain array (["A2","A3","A4","A5",,,"A8","A9",]). Then the method .filter(Boolean) strips the empty elements. The code above returns [A2, A3, A4, A5, A8, A9].

like image 103
k4k4sh1 Avatar answered Dec 04 '22 08:12

k4k4sh1