Home > Software engineering >  How can I exclude null elements from data array?
How can I exclude null elements from data array?

Time:04-21

I have been using Yuri's answer to a question, but found myself in a new situation and I haven't quite understood each step of this method here:

function myFunction() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var header = sheet.getDataRange().getValues()[0];

  var data = [
    ["ID","Variação","Nome Site","Obs"],
    [11602,185,"Camisa Teste","Teste da Observação"]
  ]

  var indexes = header.map(x => data[0].indexOf(x));
  data = data.map(x => indexes.map(i => x.slice()[0] = x[i]));

  sheet.getRange(1, 1, data.length, data[0].length).setValues(data);
}

Here's what the result looks like:

let result = [
           ["ID","Variação","Nome Site","Obs", "", ""],
           [11602,185,"Camisa Teste","Teste da Observação", "", ""]
         ]

Now, this is returning data with nulls. How can I make it return only mapped array elements? So, instead of heaving an array length of 6, that'd be only 4. Expected Result:

let expectedResult = [
           ["ID","Variação","Nome Site","Obs"],
           [11602,185,"Camisa Teste","Teste da Observação"]
         ]

Thank you!

CodePudding user response:

Remove nulls

function test() {
Logger.log(JSON.stringify([1,2,3,null,4,null,5,''].filter(e => e)))
}

Execution log
7:48:37 PM  Notice  Execution started
7:48:37 PM  Info    [1,2,3,4,5]
7:48:38 PM  Notice  Execution completed

CodePudding user response:

One way is to filter the inner values:

let result = [
  ["ID", "Variação", "Nome Site", "Obs", "", ""],
  [11602, 185, "Camisa Teste", "Teste da Observação", "", ""]
]
result = result.map(x => x.filter(y => y))
console.log(result)

  • Related