Retrieve a specific column from an array of arrays

Consider this scenario with a JavaScript array:

let x = someNumber;
let y = someOtherNumber;
let myArray = // create new x by y Array;

What is the most efficient method to extract a column (as opposed to a row) from this array?

Example structure:

getColumn = function(anArray, columnNumber){
    // check if column number exists in array
        // if it does, retrieve the column
        // if not, return null
}

Answer №1

If you are looking for the quickest way to achieve something with minimal code, then using Array.prototype.map is probably your best bet:

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

Answer №2

Here's a simple illustration that I believe showcases the concept:

let targetColumn = 3;
let selectedElements = [];
for(let j = 0; j < 10; j++) {

    let element = data[j][targetColumn];
    selectedElements.push(element);   

}

Answer №3

If you're searching for an elegant solution using ES6, this code snippet might be exactly what you need.

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

Source: Check out more at GitHub@pauloffborba

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Deprecated message received from the body-parser node module

Currently learning Node.js, I've been utilizing the 'express' framework and installed body-parser successfully. However, upon starting my app, I encountered this message from Node: body-parser deprecated bodyParser: use individual json/urle ...

Exploring Sensor Information with Vis.js

In my work with Wireless Sensor Networks, I have been collecting sensor addresses and their corresponding temperature readings in JSON format. The data looks like this: {"eui":"c10c00000000007b","count":0"tmp102":" 0.0000 C"} When it comes to the network ...

Deduce the generic types of conditional return based on object property

My goal is to determine the generic type of Model for each property. Currently, everything is displaying as unknown[] instead of the desired types outlined in the comments below. playground class Model<T> { x?: T } type ArgumentType<T> = T ...

What is the best way to display the ID value as a variable in a bootstrap modal dialog?

I originally thought figuring this out would be a breeze, but it's proving to be quite the challenge. After scouring for solutions without success, I find myself stuck. There's a list of dynamically generated buttons with unique id values that I ...

Utilizing the initial index of an array within AngularJS

Currently delving into AngularJS and I have a straightforward inquiry. When using 'orderBy', the $index points to the sorted array. Is there an easy method to refer back to the original array index before sorting? <div ng-init="names=[' ...

Webpack fails to handle CSS background images

I'm having trouble with my Webpack configuration as it's not processing CSS images set in the background property: background: url('./hero.jpg') no-repeat right; This is resulting in an error message that reads: ERROR in ./src/app/comp ...

Display a complete calendar with the date picker on a webpage

Currently experimenting with React to build a straightforward application. Admiring the appearance of full calendars from these date pickers (once clicked): Material-UI React-Toolbox Wondering if it's feasible to present the full calendar directly ...

My coding skills leave much to be desired and I am encountering some challenges with my current Hangman Game project

I recently started learning JavaScript and I'm encountering some difficulties with my code. My assignment is to create a hangman game, and I've successfully implemented the loops for displaying "right" and "wrong" letters. However, I'm strug ...

Sending an image from a NodeJS socket server to another server: The ultimate guide

Hello there, I'm currently working on a new project and I could really use your input on a challenge I'm dealing with. Here's the situation: I have a web server running a socket.io module. The server is listening on port 3012 and streaming ...

Downloading an array as a CSV file using PHP

Struggling to convert my PHP array into a downloadable CSV file. Here's how the array currently looks: Array[0] = "Name,age,ID" Array[1] = "Alex,26,1" Array[2] = "Ryan,12,2" Array[3] = "Steph,56,7" and so on... I attempted to download it as a CSV ...

Tips for correcting the `/Date(xxxxxxxxxxxxx)/` formatting issue in asp.net mvc

As a programming novice, I am trying to display data from my database server on the web using a datatable in asp.net mvc. After following a tutorial video on YouTube, I encountered an issue where the date and time columns in my table are displaying as /Dat ...

Utilizing jQuery's slice() and remove() functions, followed by triggering jQuery's isotope to reorganize

I have been working on a project for the website My goal is to display only 25 posts and rearrange the post divs (.dcsns-li) by calling Isotope again. Here is the code I am using: jQuery(window).load(function(){ var nPosts = jQuery(".dcsns-li").length ...

Nodejs - Utilizing Express and Mongoose to Implement URL Routing by Name

My Express 4 server has CRUD routes specifically for authors: router.get('/authors', AuthorsController.index); router.post('/authors', AuthorsController.store); router.get('/authors/:name', AuthorsController.show) ...

Adjusting the overflow of a parent div based on the position of the div within it by scrolling

I'm trying to create a page with 3 different sections: <div class="container" id="main-container"> <div class="section" id="profile"> Hello World </div> <div class="section" id="projects"> Hello World 2 ...

Cease the loading of a script in an HTML file

I have encountered a challenge in preventing a script from loading on my Wordpress website. The HTML file contains two scripts: <script type="0f1a6d7ca503db410c0d10c4-text/javascript" src='https://www.[-----------].se/wp-content/plugins/ ...

Incorporating Vue into a dated website by eliminating the div and replacing it with new dynamic Vue components

As I attempt to integrate Vue into my old website, I want the existing jQuery scripts to continue functioning and the old HTML content to be displayed. However, I am encountering an issue where the el element and its contents are being removed. This probl ...

Tips on populating the gap between dual cylinder meshes in Three.js

I'm working on a code that creates cylinders using a series of 3D vectors, but I'm encountering an issue with unsightly gaps between them: https://i.sstatic.net/E17Gm.png Does anyone have any tips on how to fill in these gaps in the latest vers ...

Is mastering canvas games a worthwhile pursuit?

Being passionate about creating a canvas game, I have some doubts about whether it's worth the effort. Here's why... With Adobe Flash, you can create highly complex animations, games, and apps. It makes me wonder if there will soon be a program ...

Is there a way to adjust the quantity of items in the shopping cart without the need to reload the webpage?

Currently, I am working on a test project using React & Redux. The project involves implementing a basket feature where I receive an array of products structured like this: products: [ { name: "Product one", count: 1, ...

Form Input: Retrieve Exclusive Value Using Identical Name and ID

I have successfully executed a query and displayed the results on my address page using PHP and AJAX. <div id="address-wrap"> <div id="report-address">3719 COCOPLUM CIR <br> Unit: 3548<br> COCONUT CREEK, FL 33063</div> <di ...