Home > Net >  How to return blank and not 0, while mapping through a 2D array using GAS?
How to return blank and not 0, while mapping through a 2D array using GAS?

Time:02-23

Right now, the code does divides each element by 100, so I can get it in the correct % format. However, when the element iterated is blank, it gives me 0 while this would have to be blank and I can't seem to make it right:

The data in a 2D array:

[
 ["MARLEY SC35-45 PIPE CLIP PVCu","82",1,0,11.96,-68],
 ["MARLEY SC35-45 PIPE CLIP PVCu","110",1,0,10.02,],
 ["MARLEY SC35-45 PIPE CLIP PVCu","160",1,0,32.62,-68]
]

The code I'm running returns 0, but this would have to be blank.

let dataLab3 = dataLab.map(function (v) { return [v[5]/100] })

Current result:

-68
-0
-68

..while it should be:

-68

-68

I'm not sure where I'd apply a filter in this case.

Appreciate your help.

CodePudding user response:

So add a check in the map to see if it has a value either with a truthy check

return v[5] ? [v[5]/100] : '';

or check if it is undefined if the value can be zero.

const dataLab = [
  ["MARLEY SC35-45 PIPE CLIP PVCu","82",1,0,11.96,-68],
  ["MARLEY SC35-45 PIPE CLIP PVCu","110",1,0,10.02,],
  ["MARLEY SC35-45 PIPE CLIP PVCu","160",1,0,32.62,-68]
];

const dataLab3 = dataLab.map(function (v) {
  return v[5] !== undefined ? [v[5]/100] : undefined;
});

console.log(dataLab3);

return whatever you want in the second part of the ternary operator.

CodePudding user response:

If v[5] does not exist, then return "" (or null):

let dataLab3 = dataLab.map(v => v[5] ? [v[5]/100] : "" )
  • Related