从JavaScript中的二维数组获取列

时间:2021-08-02 20:25:37

How can I retrieve a column from a two-dimensional array?

如何从二维数组中检索列?

This array has 20 columns and 3 rows and I want to get the the first row.

这个数组有20列和3行我想要得到第一行。

6 个解决方案

#1


16  

You have to loop through each element in the 2d-array, and get the nth column.

您必须循环遍历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

#2


81  

Taking a column is easy with the map function.

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

Why bother with the slice at all? Just filter the matrix to find the rows of interest.

为什么要为这片肉费心呢?只要过滤矩阵,就能找到感兴趣的行。

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

Sadly, filter and map are not natively available on IE9 and lower. The MDN documentation provides implementations for browsers without native support.

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

#3


18  

Use Array.prototype.map() with an arrow function:

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

Note: Array.prototype.map() and arrow functions are part of ECMAScript 6 and not supported everywhere, see ECMAScript 6 compatibility table.

注意:Array.prototype.map()和arrow函数是ECMAScript 6的一部分,并不是所有地方都支持,请参见ECMAScript 6兼容性表。

#4


2  

This function works to arrays and objects. obs: it works like array_column php function. It means that an optional third parameter can be passed to define what column will correspond to the indices of return.

这个函数适用于数组和对象。它的工作方式类似于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;
}

This is a conditional version:

这是一个有条件的版本:

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

usability:

可用性:

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

Output:

输出:

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


0  

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

#6


-1  

Arrays don't really have well defined rows and columns, but essentially you can only get access to an element in an array which means you can get any of the arrays contained in the outer array or an element in one of those arrays. There's no reason you can't just create a new array and read all the values in to, but if you're just searching for a value you might as well do that while looping through:

数组并没有定义良好的行和列,但是本质上你只能访问数组中的一个元素,这意味着你可以获得包含在外部数组中的任何一个数组或者这些数组中的一个元素。没有理由不创建一个新数组并读取其中的所有值,但如果只是搜索一个值,那么在循环遍历时也可以这样做:

var column = 2;
for (var i = 0; i < array.length; i++) {
    if (matchesSearch(array[i][column])) {
        // Do what you want with a matched result, perhaps store it in a result array.
    }
}

Obviously you need to implement matchesSearch so that it returns true if the value matches what you're looking for.

显然,您需要实现matchesSearch,以便它返回true,如果该值与您正在查找的值匹配。

#1


16  

You have to loop through each element in the 2d-array, and get the nth column.

您必须循环遍历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

#2


81  

Taking a column is easy with the map function.

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

Why bother with the slice at all? Just filter the matrix to find the rows of interest.

为什么要为这片肉费心呢?只要过滤矩阵,就能找到感兴趣的行。

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

Sadly, filter and map are not natively available on IE9 and lower. The MDN documentation provides implementations for browsers without native support.

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

#3


18  

Use Array.prototype.map() with an arrow function:

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

Note: Array.prototype.map() and arrow functions are part of ECMAScript 6 and not supported everywhere, see ECMAScript 6 compatibility table.

注意:Array.prototype.map()和arrow函数是ECMAScript 6的一部分,并不是所有地方都支持,请参见ECMAScript 6兼容性表。

#4


2  

This function works to arrays and objects. obs: it works like array_column php function. It means that an optional third parameter can be passed to define what column will correspond to the indices of return.

这个函数适用于数组和对象。它的工作方式类似于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;
}

This is a conditional version:

这是一个有条件的版本:

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

usability:

可用性:

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

Output:

输出:

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


0  

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

#6


-1  

Arrays don't really have well defined rows and columns, but essentially you can only get access to an element in an array which means you can get any of the arrays contained in the outer array or an element in one of those arrays. There's no reason you can't just create a new array and read all the values in to, but if you're just searching for a value you might as well do that while looping through:

数组并没有定义良好的行和列,但是本质上你只能访问数组中的一个元素,这意味着你可以获得包含在外部数组中的任何一个数组或者这些数组中的一个元素。没有理由不创建一个新数组并读取其中的所有值,但如果只是搜索一个值,那么在循环遍历时也可以这样做:

var column = 2;
for (var i = 0; i < array.length; i++) {
    if (matchesSearch(array[i][column])) {
        // Do what you want with a matched result, perhaps store it in a result array.
    }
}

Obviously you need to implement matchesSearch so that it returns true if the value matches what you're looking for.

显然,您需要实现matchesSearch,以便它返回true,如果该值与您正在查找的值匹配。