从二维数组中获取列

Get column from a two dimensional array

本文关键字:获取 二维数组      更新时间:2023-09-26

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

我使用的是这样定义的数组:

var array=[];

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

使用map函数很容易获取列。

// 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]; });

为什么要用切片呢?只需过滤矩阵以找到感兴趣的行。

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

遗憾的是,滤镜和地图在IE9和更低版本上是不可用的。MDN文档为没有本机支持的浏览器提供了实现。

使用带有箭头函数的Array.prototype.map():

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兼容性表

您必须遍历2d-array中的每个元素,并获得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
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' ]

您可以使用以下数组方法从2D数组中获取列:

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;
};

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

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

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

ES6 Javascript版本:

使用对象键:

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原型的好方法。

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));

此函数适用于数组和对象。对象:它的工作原理像array_column PHP函数。这意味着可以传递一个可选的第三个形参来定义哪个列对应于return的索引。

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 }
*/

我创建了一个库矩阵切片器来操作矩阵项。所以你的问题可以这样解决:

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

可能对某人有用。: -)

就像前面的文章一样,您可以编写一个函数来存档。但我们可以在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))

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

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