【问题标题】:Get column from a two dimensional array从二维数组中获取列
【发布时间】:2011-10-21 10:16:18
【问题描述】:

如何从二维数组中检索列而不是单个条目? 我这样做是因为我只想在其中一列中搜索一个字符串,所以如果有另一种方法可以做到这一点,请告诉我。

我正在使用这样定义的数组:

var array=[];

最后这个数组的大小是 20(col)x3(rows),我需要读取第一行并检查其中是否存在一些短语。

【问题讨论】:

    标签: javascript


    【解决方案1】:

    使用map function 可以轻松创建专栏。

    // a two-dimensional array
    var two_d = [[1,2,3],[4,5,6],[7,8,9]];
    
    // take the third column
    var col3 = two_d.map(function(value,index) { return value[2]; });
    

    为什么要为切片而烦恼呢?只需filter 矩阵即可找到感兴趣的行。

    var interesting = two_d.filter(function(value,index) {return value[1]==5;});
    // interesting is now [[4,5,6]]
    

    很遗憾,filter and map are not natively available on IE9 and lower。 MDN 文档为没有原生支持的浏览器提供了实现。

    【讨论】:

      【解决方案2】:

      Array.prototype.map()arrow function 一起使用:

      const arrayColumn = (arr, n) => arr.map(x => x[n]);
      
      const twoDimensionalArray = [
        [1, 2, 3],
        [4, 5, 6],
        [7, 8, 9],
      ];
      
      console.log(arrayColumn(twoDimensionalArray, 0));

      注意:Array.prototype.map() 和箭头函数是 ECMAScript 6 的一部分,并非所有地方都支持,请参阅 ECMAScript 6 compatibility table

      【讨论】:

      • 只是我,还是这在 js 中不必要的复杂?无论如何,这行得通,谢谢@Michal。
      【解决方案3】:

      您必须遍历二维数组中的每个元素,并获得第 n 列。

          function getCol(matrix, col){
             var column = [];
             for(var i=0; i<matrix.length; i++){
                column.push(matrix[i][col]);
             }
             return column;
          }
      
          var array = [new Array(20), new Array(20), new Array(20)]; //..your 3x20 array
          getCol(array, 0); //Get first column
      

      【讨论】:

      • 我知道我可以这样做,但我认为有一个预定义的函数或方法可以检索这些数据。无论如何,感谢您的回答。
      • @intsoumen 这个问题是关于 JavaScript,而不是 Python。
      【解决方案4】:

      您可以使用以下array methods 从二维数组中获取列:

      Array.prototype.map()

      const array_column = (array, column) => array.map(e => e[column]);
      

      Array.prototype.reduce()

      const array_column = (array, column) => array.reduce((a, c) => {
        a.push(c[column]);
        return a;
      }, []);
      

      Array.prototype.forEach()

      const array_column = (array, column) => {
        const result = [];
      
        array.forEach(e => {
          result.push(e[column]);
        });
      
        return result;
      };
      

      如果你的二维数组是正方形(每行列数相同),可以使用以下方法:

      Array.prototype.flat() / .filter()

      const array_column = (array, column) => array.flat().filter((e, i) => i % array.length === column);
      

      【讨论】:

        【解决方案5】:
        var data = [
            ["a1", "a2", "a3"],
            ["b1", "b2", "b3"],
            ["c1", "c2", "c3"]
        ];
        
        var col0 = data.map(d => d[0]); // [ 'a1', 'b1', 'c1' ]
        
        var col1 = data.map(d => d[1]); // [ 'a2', 'b2', 'c2' ]
        

        【讨论】:

          【解决方案6】:

          function arrayColumn(arr, n) {
            return arr.map(x=> x[n]);
          }
          
          var twoDimensionalArray = [
            [1, 2, 3],
            [4, 5, 6],
            [7, 8, 9]
          ];
          
          console.log(arrayColumn(twoDimensionalArray, 1));

          【讨论】:

          • 这是一个非常简洁的方法,它利用内置的 JavaScript 数组方法。
          【解决方案7】:

          Javascript 中的 ES6 版本:

          使用对象键:

          var haystack = [
           {a:1, b:2},
           {a:3, b:4},
           {a:5, b:6}
          ];
          
          var b_col = haystack.map(x => x.b); // [2,4,6]
          

          使用嵌套数组索引:

          var haystack2 = [
            [1,2,3,4,5],
            [5,4,3,2,1],
            [9,8,7,6,5],
            [5,6,7,8,9]
          ];
          
          var col_2 = haystack.map(x => x[2]); // [3,3,7,7]
          

          @Pylon 的回答也是将其添加到 Array 原型的好方法。

          【讨论】:

            【解决方案8】:

            此函数适用于数组和对象。 obs:它像 array_column php 函数一样工作。这意味着可以传递一个可选的第三个参数来定义哪个列将对应于返回的索引。

            function array_column(list, column, indice){
                var result;
            
                if(typeof indice != "undefined"){
                    result = {};
            
                    for(key in list)
                        result[list[key][indice]] = list[key][column];
                }else{
                    result = [];
            
                    for(key in list)
                        result.push( list[key][column] );
                }
            
                return result;
            }
            

            这是一个有条件的版本:

            function array_column_conditional(list, column, indice){
                var result;
            
                if(typeof indice != "undefined"){
                    result = {};
            
                    for(key in list)
                        if(typeof list[key][column] !== 'undefined' && typeof list[key][indice] !== 'undefined')
                            result[list[key][indice]] = list[key][column];
                }else{
                    result = [];
            
                    for(key in list)
                        if(typeof list[key][column] !== 'undefined')
                            result.push( list[key][column] );
                }
            
                return result;
            }
            

            可用性:

            var lista = [
              [1, 2, 3],
              [4, 5, 6],
              [7, 8, 9]
            ];
            
            var obj_list = [
              {a: 1, b: 2, c: 3},
              {a: 4, b: 5, c: 6},
              {a: 8, c: 9}
            ];
            
            var objeto = {
              d: {a: 1, b: 3},
              e: {a: 4, b: 5, c: 6},
              f: {a: 7, b: 8, c: 9}
            };
            
            var list_obj = {
              d: [1, 2, 3],
              e: [4, 5],
              f: [7, 8, 9]
            };
            
            console.log( "column list: ", array_column(lista, 1) );
            console.log( "column obj_list: ", array_column(obj_list, 'b', 'c') );
            console.log( "column objeto: ", array_column(objeto, 'c') );
            console.log( "column list_obj: ", array_column(list_obj, 0, 0) );
            
            console.log( "column list conditional: ", array_column_conditional(lista, 1) );
            console.log( "column obj_list conditional: ", array_column_conditional(obj_list, 'b', 'c') );
            console.log( "column objeto conditional: ", array_column_conditional(objeto, 'c') );
            console.log( "column list_obj conditional: ", array_column_conditional(list_obj, 0, 0) );
            

            输出:

            /*
            column list:  Array [ 2, 5, 8 ]
            column obj_list:  Object { 3: 2, 6: 5, 9: undefined }
            column objeto:  Array [ undefined, 6, 9 ]
            column list_obj:  Object { 1: 1, 4: 4, 7: 7 }
            
            column list conditional:  Array [ 2, 5, 8 ]
            column obj_list conditional:  Object { 3: 2, 6: 5 }
            column objeto conditional:  Array [ 6, 9 ]
            column list_obj conditional:  Object { 1: 1, 4: 4, 7: 7 }
            */
            

            【讨论】:

              【解决方案9】:

              我创建了一个库matrix-slicer 来处理矩阵项。所以你的问题可以这样解决:

              var m = new Matrix([
                  [1, 2],
                  [3, 4],
              ]);
              
              m.getColumn(1); // => [2, 4]
              

              可能对某人有用。 ;-)

              【讨论】:

                【解决方案10】:

                就像之前的帖子一样,您可以编写一个函数来归档。但我们可以在Array.prototype 上添加函数,如下所示:

                Array.prototype.column = function(i) {
                  try { 
                    return this.map( x => x[i]);
                  } catch (e) {
                    // catch error: out of index or null array ....
                    console.log(e);
                  }
                }
                
                let array =
                [[`animal`,`carnivours`],
                 [`cow`,`milk`],
                 [`plant`,`small`],
                 [`fish`,`tank`]];
                  
                console.log(array.column(0))
                console.log(array.column(1))

                我认为它肯定更优雅。

                【讨论】:

                  【解决方案11】:

                  还有一种使用.bind()的方法。

                  function getColumn(twoDArr,columnIndex){
                      function getCol(value){
                         return [value[columnIndex]]
                      } 
                      return twoDArr.map(getCol.bind(columnIndex));
                  }
                  

                  【讨论】:

                    猜你喜欢
                    • 1970-01-01
                    • 2022-01-06
                    • 1970-01-01
                    • 2010-11-09
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    • 2013-05-14
                    相关资源
                    最近更新 更多