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

后端 未结 4 1383
孤独总比滥情好
孤独总比滥情好 2021-01-06 16:55

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 i

4条回答
  •  忘掉有多难
    2021-01-06 17:10

    If you don't have empty cells in between it's actually pretty easy.

    var lastRow = sheet.getLastRow();
    var array = sheet.getRange('A1:A' + lastRow).getValues();
    

    If you need to weed out empty entries after that, you can use a for statement, or to be faster, filter like an earlier answer shows.

    var filteredArray = array.filter(function(n){ return n != '' });
    

    The main difference between this answer and the one posted earlier that I mentioned is that getValues() will give you an array.

    I've tested this and it works in google apps script, and it does not time out when I use the array, or even when I put in large amounts of data (I tested it with an array that has about 20-50 characters per entry and about 500 entries). Just make sure to define the var sheet or put in your own variable.

提交回复
热议问题