从二维数组中获取列

时间:2011-10-21 10:16:19

标签: javascript

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

我正在使用以这种方式定义的数组:

var array=[];

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

10 个答案:

答案 0 :(得分:102)

使用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文档为没有本机支持的浏览器提供了实现。

答案 1 :(得分:28)

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

答案 2 :(得分:20)

你必须循环遍历2d阵列中的每个元素,并获得 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

答案 3 :(得分:7)

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' ]

答案 4 :(得分:2)

此函数适用于数组和对象。 obs:它的工作方式类似于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 }
*/

答案 5 :(得分:1)

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

var m = new Matrix([
    [1, 2],
    [3, 4],
]);

m.getColumn(1); // => [2, 4]

可能对某人有用。 ;-)

答案 6 :(得分:1)

您可以使用以下array methods从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);

答案 7 :(得分:1)

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

我认为它绝对更优雅。

答案 8 :(得分:0)

&#13;
&#13;
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));
&#13;
&#13;
&#13;

答案 9 :(得分:0)

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

相关问题