What is the best method for extracting various columns from a two-dimensional array?

Can you provide me with some assistance in JavaScript on how to extract multiple columns from a two-dimensional array similar to the example below?

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

I have come across methods like forEach or map that allow extracting one column at a time. Is it possible to nest these methods to extract multiple specific columns based on their index?

For instance, if I want columns 1, 2, and 4 as output.

Output = [
  [1, 2, 4],
  [5, 6, 8],
  [9, 10, 12],
];

UPDATE:

Another challenge I am facing is removing any row where Array[i][1] equals 0 or is empty.

If we introduce additional elements into the array...

Array = [
  [1, 2, 3, 4],
  [5, 6, 7, 8],
  [9, 10, 11, 12],
  [13, 0, 15, 16],
  [17, , 19, 20],
  [21, 22, 23, 24],
]; 

The desired output should be...

Output = [
  [1, 2, 4],
  [5, 6, 8],
  [9, 10, 12],
  [21, 22, 24],
]; 

Answer №1

To obtain the values at each column for each row in array arr, you can use the .map() method to map each row to a new array. Inside this mapping process, you can utilize another .map() on an array of columns or indexes that you wish to extract the values from. This nested map operation will retrieve and map each index to its associated value from the row.

Here is an example showcasing this approach:

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

const cols = [1, 2, 4];
const res = arr.map(r => cols.map(i => r[i-1]));
console.log(res);

The inner mapping function loops through the indexes specified in the cols array and retrieves the corresponding values from the current row. For instance, if we consider the second array in arr:

[5, 6, 7, 8]

Executing cols.map(...) will iterate over each element in [1, 2, 4]. Each element is transformed into a new value as follows:

i = 1
r = [5, 6, 7, 8]
new value: r[1-1] = 5

Subsequently, the next element in cols is processed:

i = 2
r = [5, 6, 7, 8]
new value: r[2-1] = 6

Lastly, the final element in cols is examined:

i = 4
r = [5, 6, 7, 8]
new value: r[4-1] = 8

Thus, the mapping function generates a new array containing the values located at the specified indexes in the current row ([5, 6, 8]). This process repeats for each inner array or row, resulting in the final output.


UPDATE Following your recent modification, you can apply the same concept described above to filter your arrays based on specific columns of interest. After extracting the desired columns, you can utilize .filter() to retain only the rows with a truthy value in the second column. By keeping arrays with truthy second column values, those with non-truthy values (falsy values) such as 0 or undefined are omitted from the final array.

Check out the following example:

const arr = [
  [1, 2, 3, 4],
  [5, 6, 7, 8],
  [9,10,11,12],
  [13,0,15,16],
  [17, ,19,20],
  [21,22,23,24],
]

const cols = [1, 2, 4];
const col = 2;
const res = arr.filter(r => r[col-1]).map(r => cols.map(i => r[i-1]));
console.log(res);

If there are multiple columns you want to exclude, you can employ .every() to validate that each column contains a truthy value. If every column meets this condition, .every() returns true, maintaining the column; otherwise, it returns false, eliminating the column:

const arr = [
  [1, 2, 3, 4],
  [5, 6, 7, 8],
  [9,10,11,12],
  [13,0,15,16],
  [ ,17,19,20],
  [21,22,23,24],
]

const cols = [1, 2, 4];
const col = [1, 2];
const res = arr.filter(r => col.every(c => r[c-1])).map(r => cols.map(i => r[i-1]));
console.log(res);

Answer №2

One approach to tackle this is by utilizing the index parameter within the filter method.

Array.filter(currElem, index, array)

Given that arrays are 0-indexed, I have constructed an array with the desired indices [0, 1, 3]. To implement this solution, both the data array and index array need to be passed into the function.

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

var arrIndex = [0, 1, 3];

function extractData(arr, indexArr) {

  return arr.map(obj => {  
      return obj.filter((ob, index) => {
          if(indexArr.includes(index)) {return ob}
      })
  })
}

console.log(extractData(array, arrIndex));

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

Obtaining a value from a protractor promise within a function and returning it

Is there a way to extract text from a webpage and use it for asserting on another element in the specification? Here is a simple example that demonstrates how you cannot return a value from a function within a Protractor promise: describe('My Test&a ...

Having difficulty attaching data in Angular 2

I am attempting to populate the countries data into my px-component, which happens to be a typeahead. You can find the Codepen link here. When I directly bind the data in HTML, the typeahead successfully suggests a list of countries. However, when I atte ...

What is the best way to access the data stored within a Promise object in a React application?

Below is the snippet of my code that handles parsing application data: async function parseApplication(data: Application) { const fieldGroupValues = {}; for (const group of Object.keys(data.mappedFieldGroupValues)) { const groupValue = data.mappedF ...

Visualizing Data with d3.js Force Chart: Integrating Images with Nodes for Dynamic Animation

After enhancing a force diagram to compare two profiles, I am faced with the challenge of getting the main node to display an image. View comparison here How can I centrally align and size the image correctly while making the thumbnail data from the JSO ...

Having trouble with Angular UI Select functionality?

I have integrated the angular ui select library from https://github.com/angular-ui/ui-select into my project. Instead of using the traditional select element, I am now utilizing the ui-select directive. This is a snippet of my code: <select class=" ...

Issue: Unable to update reference: The primary argument includes an invalid key

Encountering a curious error on Firebase while working with Vue.js: The process goes smoothly the first time, and I can execute the following function multiple times without any issues. addSpace: function (newSpace) { let userId = firebaseApp.auth(). ...

Tips for altering the visibility of a different class on hover using jss

Exploring the features of material ui react Below is my scss code snippet (when hovering over .content, the .replyBtn becomes visible): .content { &:hover { .replyBtn { visibility: visible } } } .replyBtn { visibility: hidden; } ...

Discover the specific item within an array of objects

Anyone have information like this: const info = { Title : "Banana", Quantity : 10, Location : "Everywhere", Phone : 123456, A : 987, B : 654, } and there is another array of details as: const dataArr = ["Title",&q ...

What is the best method to send a HTTP request (specifically for scraping) to an Angular2 website?

I am attempting to utilize a node server to extract data from an angular2 application. However, the issue I am encountering is that the response I receive is just the index.js file, which essentially represents the "loading..." section of the webpage. My ...

JavaScript: A guide to finding CSS properties within a string

Checking for CSS Properties in Over 1,000 Sentences Is there a way in Javascript to check sentences against a built-in CSS index? Currently… If I need to search for CSS properties in the sentences below, I have to create an array containing all the CS ...

The width values in the array are constantly shifting upon refreshing

Would it be possible to create an array called slide_widths, which will contain the widths of all the .slide elements? $( document ).ready(function() { var $slider = $('.slider ul'); var slider_width = $slider.width(); var $slides = $(&apo ...

Loading New Page When Iframe is Loaded

I am currently working with an iframe that reflects the appscript I have created. Is there a way to automatically redirect the user to a different page when they change a link or submit a form within the iframe? <div class="embed-responsive em ...

Steps to initiate my selenium-standalone server: Execute the command "selenium-standalone start"

I'm currently facing a challenge while trying to execute a test script in WebDriverIO. After cloning the code from wdio-cucumber-framework, I am unable to get selenium-standalone to start properly. The error message indicates an issue with geckodriv ...

Issue with Vue js variable not functioning properly when the page is in operation

Trying to integrate vue.json into my asp.net mvc project by downloading vue.js from the nuget package and dragging it into the layout. After running the project, I encountered the following output: Code output https://i.sstatic.net/ZGRpN.png or this http ...

Unraveling the mysteries of JQuery AJAX POST and Serialization techniques!

I am struggling to implement an AJAX request using JQuery to validate and submit a form, extract its values, and assign them to variables for further use. Unfortunately, I lack a clear understanding of AJAX functionality as well as how serializing works. ...

Is there a way to dynamically refresh the Bing web API search results on a React.js application after entering a search query in the search bar (in the SER

I've been using the Bing Web Search API to access data by typing a query into a search bar I created. However, I've been facing an issue where the data isn't displaying in the search results when I submit the query. I'm specifically try ...

In VueJS 3, the data within the app.component instance will lack reactivity if it is declared within the data() or setup() functions

When it comes to declaring new reactive variables inside a component, I faced an interesting issue. It seems that setting the component globally, outside the app.component instance, and then returning it to either the data() or setup() function works perfe ...

Expand the HTML Template and Resize Children to Fit the Window

My software creates HTML email templates that typically range from 600px to 650px in width, but can sometimes be as wide as 900px. The templates have nested table elements for email clients, with all dimensions specified in fixed pixels rather than relativ ...

Tips for interpreting JSONP objects

After setting up this HTML file to send a GET request to the random word API (wordnik) server, I received a response that looked like this: [{"id":2998982,"word":"failproof"}] My goal is to extract the "word" part from the response, but I'm struggli ...

What is the optimal method for storing a binary tree on a server?

I am looking to efficiently store a binary tree on my server for use in the IOS and Android applications of all my users. What is the most optimal method (in terms of speed) to accomplish this task? Edit: It is necessary for all my users to be able to up ...