Search code examples
javascriptgoogle-sheetsspreadsheet

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


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.


Solution

  • 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