Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

253
Views
How can I map through a 2D array using a Condition?

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

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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]));

about 4 years ago · Juan Pablo Isaza Report

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!