Convert 2D array indices to spreadsheet cell co-ordinates in JavaScript

46 Views Asked by At

Pretty self-explanatory, but given 2D array indices (as CSV), how do I convert it to a spreadsheet cell coordinates? For example, "0, 0" would output "A1", "3, 4" would be "D5", etc.

2

There are 2 best solutions below

0
TheMaster On BEST ANSWER

Split and convert strings to number and use String.fromCodePoint:

/*<ignore>*/console.config({maximize:true,timeStamps:false,autoScroll:false});/*</ignore>*/ 
const csv = "2, 1";
const parseIndicesToA1 = str => str.split(", ").map(Number).reduce((a,c)=>String.fromCodePoint(65+a)+(c+1));
console.log(parseIndicesToA1(csv))
<!-- https://meta.stackoverflow.com/a/375985/ -->    <script src="https://gh-canon.github.io/stack-snippet-console/console.min.js"></script>

For >=26, see Convert column index into corresponding column letter

0
Century Tuna On

SUGGESTION:

Try this:

function myFunction() {

  var sample = [[0,0],[3,4]]; //your sample 2d array
  var ss = SpreadsheetApp.getActiveSpreadsheet(); 
  var sheet = ss.getActiveSheet();
  sample.forEach(x => console.log(sheet.getRange(x[1] + 1, x[0] +1).getA1Notation()) ) 

}

Log results:

image

Reference:

https://developers.google.com/apps-script/reference/spreadsheet/range#geta1notation