13

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
}
  • 2
    See http://stackoverflow.com/questions/7848004/get-column-from-a-two-dimensional-array – OnlyThenDidIReckonMyCurse Jan 14 '14 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 Jan 14 '14 at 22:18
  • whoops. fixed using pseudocode above. –  Jan 14 '14 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 Jan 14 '14 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 Jan 14 '14 at 22:29
  • @adeneo, Yes, a 2D array is an array of arrays... but that is, essentially, a matrix (or a table), which has rows and columns. Javascript (among other languages) can even initialize a 2D array in such a way that it _looks_ like a maxtrix: http://jsfiddle.net/Am8Bq/ (Similarly, a 3D array can be visualized as a cuboid, although there's no means to display that in code on a 2D screen!) – Brian S Jan 14 '14 at 22:33

3 Answers3

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));
Ry-
  • 218,210
  • 55
  • 464
  • 476
1

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

}
0

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

GokuH12
  • 1
  • 1