skip to Main Content

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?

2

Answers


  1. 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>
    Login or Signup to reply.
  2. One way to do that is to transpose the array, replace one row, and re-transpose, like this:

    function test() {
      const 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]
      ];
      const newRank = ['a', 'b', 'c', 'd'];
      console.log(replaceColumn_(table, 6, newRank));
    }
    
    function replaceColumn_(array, rowIndex, values) {
      const _transpose = a => Object.keys(a[0]).map(c => a.map(r => r[c]));
      const newArray = _transpose(array);
      newArray[rowIndex] = values;
      return _transpose(newArray);
    }
    

    See Object.keys().

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search