0

Currently I have a cell containing an array, eg A1 has [1,2,3]. I managed to get the value from the cell and tried to turn it into an array but it’s not working. Is it possible?

arrValue = cellValue // cell that was pass to the function, eg [1,2,3]
arr = Array(arrValue)
Logger.log(arr[0]) // prints [1,2,3]
Ghifax
  • 23
  • 3
  • As the additional information, if `[1,2,3]` is put in a cell and you retrieve the value using `getValue` and `getValues`, the retrieved value is the string type. So in this case, the value is `"[1,2,3]"`. In your script, when `arr = Array("[1,2,3]")` is used, `arr` is `["[1,2,3]"]`. So `arr[0]` returns `[1,2,3]`. In this case, `[1,2,3]` is `"[1,2,3]"` which is the string. I think that the reason of `Logger.log(arr[0]) // prints [1,2,3]` is due to this. Also please be careful this. – Tanaike Sep 13 '20 at 22:35
  • Does this answer your question? [Convert string array to array in javascript](https://stackoverflow.com/questions/41402834/convert-string-array-to-array-in-javascript) – Marios Sep 13 '20 at 23:24

2 Answers2

0

If it's a valid json string, use JSON.parse:

const jsonArr = /*cellValue*/ '[1,2,3]';
const arr = JSON.parse(jsonArr);
console.info({isArray: Array.isArray(arr),length:arr.length,element_1:arr[0]})
TheMaster
  • 45,448
  • 6
  • 62
  • 85
0

If the cellValue is in fact gotten as a string, then of course the answer you will be getting is the whole array.

What you can do instead is to declare your values as an array, like this:

 var arrValue = [1,2,3]
 var arr = arrValue;
 Logger.log(arr[0]) // prints 1.0
ale13
  • 5,679
  • 3
  • 10
  • 25