2

I have a script in which the row data of a google sheet is stored into a JSON. I'd like to filter the data that is stored in the array.I don't want the empty cells to be inserted into the array. I want only the filled cells to be inserted into the array .Here is the script I'm using

  var dataArray = [];
  var rows = sheet.getRange(2,1,sheet.getLastRow()-1, sheet.getLastColumn()).getValues();

  for(var i = 0, l= rows.length; i<l ; i++){
    var dataRow = rows[i];
    var record = {};
    record['name'] = dataRow[0];
    record['age'] = dataRow[1];
    record['weight'] = dataRow[2];

    dataArray.push(record);   
  } 
8
  • How do you know if a cell is empty or not? Commented Dec 18, 2018 at 18:53
  • The cells are copied from another sheet. So, the array records all the copied range even if the cell is empty. Commented Dec 18, 2018 at 18:54
  • Right. And you want to filter out empty cells. So, how do you know if a cell is empty? Will dataRow[0] be undefined for example? Commented Dec 18, 2018 at 18:55
  • I found elements like this in the array "name":" " Commented Dec 18, 2018 at 18:58
  • What does the rows array return? Please log it to the console and add the code.@AhmadSayedAbdulrahman Commented Dec 18, 2018 at 19:35

1 Answer 1

2

I think what you're really looking for is the .filter method to get rid of the empty cells, and then you can use a .map to transform them:

var rows = sheet.getRange(
  2,
  1,
  sheet.getLastRow() - 1,
  sheet.getLastColumn()
).getValues();

var filteredDataArray = rows.filter(function(row) {
  return row[0] !== ''; // Based on your comment that "empty" means it's an empty string
});

var transformedDataArray = filteredDataArray.map(function(row) {
  return { name: row[0], age: row[1], weight: row[2] };
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.