Home > Blockchain >  How can I map through a 2D array using a Condition?
How can I map through a 2D array using a Condition?

Time:06-07

I'm trying to create a formula to Google Sheets using Google Script, I have two arrays, something like this:

  • Arr1 = [1000,2000,3000,4000]
  • Arr2 = [True,False,False,True]

and I would like to do some calculate (example: multiply by 2) only over the corresponding "True". First I tried to create a method zip to turn both arrays into a 2D Array:

const zip = (a1, a2) => a1.map((x, i) => [x, a2[i]]);

It worked, but since the Google Documentation says using "map" is the best way to create formulas, how can I use map, to go over the new 2D array, returning 0 when its "false", and doing my calculation when its "true"?

Google documentation about using method map: https://developers.google.com/apps-script/guides/sheets/functions

CodePudding user response:

You don't need to create the zip map you're creating above, as long as both arrays are the same length, you can map through the first array then access the current index of the second array and check if it's true in this location, if it is run the mathematical operation (which I stored inside a function), if it's false put 0 in it's place. See below:

const arr1 = [1000, 2000, 3000, 4000];
const arr2 = [true, false, true, true];

function whatYouWantToDo(x) {
  return x * 2;
}

console.log(arr1.map((x, i) => [arr2[i] ? whatYouWantToDo(x) : 0]));

CodePudding user response:

var Arr1 = [1000,2000,3000,4000];
var Arr2 = [true,false,false,true];
console.log(Arr1.map((value, index) => value   (value * Number(Arr2[index]))));

  • Related