2

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.

Marios
  • 26,333
  • 8
  • 32
  • 52
jf12
  • 59
  • 1
  • 4
  • 3
    You don't need to select them all. You just need to loop over the outer array and then change the `[1]`st element – Taplar Dec 14 '20 at 23:01
  • 2
    Look at [forEach()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach) or [`map()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) or see: [for-each-over-an-array-in-javascript](https://stackoverflow.com/questions/9329446/for-each-over-an-array-in-javascript) – pilchard Dec 14 '20 at 23:02
  • `const yourArray = [[1,2,3], [4,5,6]]; for(let a of yourArray){ a[1] *= 2; }`. Of course, that will affect the original Arrays, so you might want to make a slice of the Arrays you don't want changed. – StackSlave Dec 14 '20 at 23:19
  • Could you not just multiply each array by another variable set to [1,2,1]? – Erik Tyler Dec 14 '20 at 23:28

2 Answers2

3

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);
Marios
  • 26,333
  • 8
  • 32
  • 52
2

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);
}
Cooper
  • 59,616
  • 6
  • 23
  • 54