jf12
jf12

Reputation: 59

How to manipulate the same element in multiple arrays

I have a script on google sheets that calls an API and the response is an Array with multiple arrays, like this:

[[1,2,3], [4,5,6]...etc]

I'm trying to do something like trying to multiply the second element of each array by 2, while keeing the other elements. I have the whole array assigned to a variable but I can't figure out how to select the 2nd element of all arrays.

Upvotes: 2

Views: 97

Answers (2)

Marios
Marios

Reputation: 27390

Another solution using map:

 const arr = [[1,2,3], [4,5,6]];
 const farr = arr.map(r=>[r[0],r[1]*2,r[2]]);
 console.log(farr);

Upvotes: 3

Cooper
Cooper

Reputation: 64110

Put a few columns of values on a spreadsheet. This function will put the same values right next to it with the second element in each row multiplied by two.

function multiply2ndElementOfEachRowBy2() {
  const ss=SpreadsheetApp.getActive();
  const sh=ss.getActiveSheet();
  const rg=sh.getRange(1,1,sh.getLastRow(),sh.getLastColumn());
  const arr=rg.getValues();
  arr.map(r=>{r[1]=r[1]*2;return r;}); 
  sh.getRange(1,sh.getLastColumn()+1,arr.length,arr[0].length).setValues(arr);
}

Upvotes: 2

Related Questions