Languages
[Edit]
EN

JavaScript - get column from two dimensional array

0 points
Created by:
Wiktor-Sribiew
860

In this article, we would like to show you how to get a column from a two-dimensional array in JavaScript.

1. Looping through elements

In this example, we create a reusable function that loops through each element in the 2D array and returns the columnIndex column.

// ONLINE-RUNNER:browser;

function getColumn(array, columnIndex) {
    var result = new Array(array.length);
    for (var i = 0; i < array.length; ++i) {
        result[i] = array[i][columnIndex];
    }
    return result;
}


// Usage example

var array = [
    ['00', '01', '02'],
    ['10', '11', '12'],
    ['20', '21', '22'],
];

console.log(getColumn(array, 0)); // [ '00', '10', '20' ]
console.log(getColumn(array, 1)); // [ '01', '11', '21' ]
console.log(getColumn(array, 2)); // [ '02', '12', '22' ]

2. Using array map() method

In this section, we use array map() method to get the columnIndex column from the array.

// ONLINE-RUNNER:browser;

const getColumn = (array, columnIndex) => array.map((element) => element[columnIndex]);


// Usage example

const array = [
    ['00', '01', '02'],
    ['10', '11', '12'],
    ['20', '21', '22'],
];

console.log(getColumn(array, 0)); // [ '00', '10', '20' ]
console.log(getColumn(array, 1)); // [ '01', '11', '21' ]
console.log(getColumn(array, 2)); // [ '02', '12', '22' ]

 

References

  1. Array.prototype.map() - JavaScript | MDN

Alternative titles

  1. JavaScript - get column of two dimensional array
  2. JavaScript - get column from 2D array
  3. JavaScript - get column of 2D array
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join