javascriptgoogle-apps-scriptmultidimensional-array

Overwrite a column of an array in AppScript


Say I have a 2D array with n rows, e.g.

table = [["Team 1", 3, 3, 0, 0, 9, 1],
         ["Team 2", 3, 0, 1, 2, 1, 3],
         ["Team 3", 3, 2, 0, 1, 6, 2],
         ["Team 4", 3, 0, 1, 2, 1, 3]]

Then say I have a 1D array of length n, e.g.

newRank = [1, 4, 2, 3]

How would I overwrite column i of table with newRank? E.g. column 6

Is there such thing as column slicing as in Python's Numpy?


Solution

  • There is no such thing as column slicing in JavaScript. You have to loop through. To do it in place,

    /*<ignore>*/console.config({maximize:true,timeStamps:false,autoScroll:false});/*</ignore>*/
    table = [["Team 1", 3, 3, 0, 0, 9, 1],
         ["Team 2", 3, 0, 1, 2, 1, 3],
         ["Team 3", 3, 2, 0, 1, 6, 2],
         ["Team 4", 3, 0, 1, 2, 1, 3]];    
    newRank = [1, 4, 2, 3];   
    col = 6; 
    newRank.forEach((v,r) => table[r][col]=v);
    console.table(table)
    <!-- https://meta.stackoverflow.com/a/375985/ -->    <script src="https://gh-canon.github.io/stack-snippet-console/console.min.js"></script>