Javascript 从二维数组中获取列
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7848004/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get column from a two dimensional array
提问by Ameen
How can I retrieve a column from a 2-dimensional arrayand not a single entry? I'm doing this because I want to search for a string in one of the columns only so if there is another way to accomplish this please tell me.
如何从二维数组而不是单个条目中检索列?我这样做是因为我只想在其中一列中搜索一个字符串,所以如果有另一种方法可以实现这一点,请告诉我。
I'm using the array defined this way:
我正在使用以这种方式定义的数组:
var array=[];
At the end the size of this array is 20(col)x3(rows) and I need to read the first row and check the existence of some phrase in it.
最后,该数组的大小为 20(col)x3(rows),我需要读取第一行并检查其中是否存在某个短语。
采纳答案by Rob W
You have to loop through each element in the 2d-array, and get the nth column.
您必须遍历二维数组中的每个元素,并获得第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
回答by Leif Carlsen
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 filterthe 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 文档为没有本机支持的浏览器提供了实现。
回答by Micha? Per?akowski
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()
和箭头函数是 ECMAScript 6 的一部分,并非所有地方都支持,请参阅ECMAScript 6 兼容性表。
回答by Grant Miller
You can use the following array methodsto obtain a column from a 2D array:
您可以使用以下数组方法从二维数组中获取列:
Array.prototype.map()
Array.prototype.map()
const array_column = (array, column) => array.map(e => e[column]);
Array.prototype.reduce()
Array.prototype.reduce()
const array_column = (array, column) => array.reduce((a, c) => {
a.push(c[column]);
return a;
}, []);
Array.prototype.forEach()
Array.prototype.forEach()
const array_column = (array, column) => {
const result = [];
array.forEach(e => {
result.push(e[column]);
});
return result;
};
If your 2D array is a square (the same number of columns for each row), you can use the following method:
如果您的二维数组是正方形(每行的列数相同),则可以使用以下方法:
Array.prototype.flat() / .filter()
Array.prototype.flat() / .filter()
const array_column = (array, column) => array.flat().filter((e, i) => i % array.length === column);
回答by MEHNAZ HUSSAIN
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));
回答by Alexandr
I have created a library matrix-slicerto manipulate with matrix items. So your problem could be solved like this:
我创建了一个库矩阵切片器来操作矩阵项。所以你的问题可以这样解决:
var m = new Matrix([
[1, 2],
[3, 4],
]);
m.getColumn(1); // => [2, 4]
Possible it will be useful for somebody. ;-)
可能它对某人有用。;-)
回答by Doglas
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.
此函数适用于数组和对象。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;
}
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 }
*/