最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Get column in array of arrays - Stack Overflow

programmeradmin0浏览0评论

Given a JavaScript array:

var m = someNumber;
var n = someOtherNumber;
var myArray = // new m x n Array;

What's the fastest way to get a column (rather than a row) from the array?

Ex structure:

getColumn = function(anArray, columnNumber){
    //if( column number exists in array)
        //get column
    //else
        //return null
}

Given a JavaScript array:

var m = someNumber;
var n = someOtherNumber;
var myArray = // new m x n Array;

What's the fastest way to get a column (rather than a row) from the array?

Ex structure:

getColumn = function(anArray, columnNumber){
    //if( column number exists in array)
        //get column
    //else
        //return null
}
Share Improve this question edited Jan 14, 2014 at 22:20 asked Jan 14, 2014 at 22:13 user1958502user1958502 6
  • 2 See stackoverflow.com/questions/7848004/… – OnlyThenDidIReckonMyCurse Commented Jan 14, 2014 at 22:18
  • Not sure I get what is supposed to be the column and what is supposed to be the row here, I guess you really mean index and value ? – adeneo Commented Jan 14, 2014 at 22:18
  • whoops. fixed using pseudocode above. – user1958502 Commented Jan 14, 2014 at 22:20
  • @adeneo, In a 2-dimensional array, the construction is generally [row][col] (and m,n is common for matrices in mathematics). This is particularly clear when an array is initialized on multiple lines. – Brian S Commented Jan 14, 2014 at 22:21
  • @BrianS - Thanks for the explanation, for me a 2D javascript array is just an array of arrays, and I've never really seen them as rows and columns, but it's probably just my simple mind not getting why it would be easier to treat 2D arrays that way, in javascript that is, in languages that actually have arrays with named keys and more strucure I see the benefit. – adeneo Commented Jan 14, 2014 at 22:29
 |  Show 1 more comment

3 Answers 3

Reset to default 12

The “fastest” in terms of “least code” would probably be Array.prototype.map:

const getColumn = (anArray, columnNumber) =>
    anArray.map(row => row[columnNumber]);

const getColumn = (anArray, columnNumber) =>
    anArray.map(row => row[columnNumber]);


const arr = [
    [1, 2, 3, 4],
    [5, 6, 7, 8],
    [9, 10, 11, 12],
];

console.log(getColumn(arr, 0));

Below is a quick example i think:

var column_number = 2;
var column = [];
for(var i=0; i<9; i++) {

    var value = matrix[i][column_number];
    column.push(value);   

}

This could help for anyone looking for a nice way to do it in ES6

 let extractColumn = (arr, column) => arr.map(x=>x[column]);

Reference: GitHub@pauloffborba

发布评论

评论列表(0)

  1. 暂无评论