Generate a smaller set of information by choosing specific columns within a two-dimensional JavaScript array

Apologies for the simplicity of my question and my limited knowledge in javascript. I am completely new to this language and need some guidance. I have an array of data and I want to extract a subset based on selected columns. Here is a snippet of the initial data:

0: {ID: 3607, Name: 'Alamo', Funds: 52933955, Revenues: 9160109, BAT: 5, …}

1: {ID: 3539, Name: 'Alvin', Funds: 6128147, Revenues: 964083, BAT: 0, …}

2: {ID: 3540, Name: 'Amarillo', Funds: 12450969, Revenues: 1716038, BAT: 0, …}

I aim to create a new array from columns 0, 1, 2, and 4 (ID, Name, Funds, and BAT). In the provided code block, toolData represents the original dataset ('toolData.json') while tableData indicates the new array being formed. The selections variable holds the numbers of the desired columns.

var getData = () => axios.get('toolData.json')
  .then(res => res.data)
  .then(data => {
    
    var toolData = data;
    console.log(toolData);
    
    var tableData = [];
    var selections = [0,1,2,4];

    for (i=0; i < toolData.length; i++)
    {
      tableData[i] = toolData[i];
      for (j=0; j<selections.length; j++)
      { 
        k = selections[j],
        tableData[i][j] = toolData[i][k]
      }
    }
    console.log(tableData);

This specific code excerpt seems to be causing issues as it appears to result in an infinite loop. By removing tableData[i] = toolData[i];, the loop issue vanishes but the code still doesn't function correctly. While console.log(toolData); outputs the complete dataset as expected, console.log(tableData); displays an error message:

javascript.js:42 Uncaught (in promise) TypeError: Cannot set properties of undefined (setting '0')
    at javascript.js:42

My ultimate goal is to allow users to select the columns they wish to include in the new array. However, before implementing that feature, I must address this current challenge.

Answer №1

It appears that each index in the array is an object based on your explanation. For example, arr[0][0]==undefined, but arr[0]['ID']==3607

function extractSubset(arr,dataToSelect){
  //arr represents the fetched array, dataToSelect contains the keys (e.g., ID, Name) that you want to extract from the array
  return arr.map(obj=>{
    var selectedData={} //object containing the desired keys for each element in the array
    dataToSelect.forEach(key=>selectedData[key]=obj[key]) //populating selectedData with wanted keys
    return selectedData
  })
}

//example of usage
var fetchData = () => axios.get('toolData.json')
  .then(res => res.data)
  .then(data => { 
    var desiredKeys=["ID","Name","Funds","BAT"]
    console.log(extractSubset(data,desiredKeys))
    //add the rest of your code here

LIVE DEMO

var dataArray=[{ID: 3607, Name: 'Alamo', Funds: 52933955, Revenues: 9160109, BAT: 5},   {ID: 3539, Name: 'Alvin', Funds: 6128147, Revenues: 964083, BAT: 0},   {ID: 3540, Name: 'Amarillo', Funds: 12450969, Revenues: 1716038, BAT: 0}]
function extractSubset(arr,dataToSelect){
  //arr is the fetched array, dataToSelect is an array of the keys(like ID,Name...) that you want from the array
  return arr.map(obj=>{
    var toReturn={} //object that would give each desired key for each part in arr
    dataToSelect.forEach(key=>toReturn[key]=obj[key]) //placing wanted keys in toReturn
    return toReturn
  })

console.log(extractSubset(dataArray,["ID","Name","Funds","BAT"]))

Answer №2

The information is stored in a JSON format, organized by names rather than numerical indexes.

It is advised to utilize the map function that comes built-in for this purpose.

const tableData = toolData.map(row => ({
    ID: row.ID,
    Name: row.Name,
    Funds: row.Funds,
    BAT: row.BAT
}));

If you prefer the new toolData array to consist of arrays instead of objects, you can achieve this with:

const tableData = toolData.map(row => [
    row.ID,
    row.Name,
    row.Funds,
    row.BAT
]);

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

Encountered an issue while compiling code using the Istanbul plugin

I'm currently working on generating a code coverage report for my ReactJS project using the babel-istanbul-plugin. However, when I incorporate "istanbul" as a plugin in my .babelrc file and attempt to build, I encounter the following error: ERROR in ...

PHP: Converting a string with array expression into a usable array

When working with an array of user inputs stored in $atts as key=>value pairs, some of the values can be in the form of an array expression like this: 'setting' => 'array(50,25)' In such cases, it is necessary to convert the arr ...

A Comprehensive Guide to Handling Errors in Angular 4: Passing the err Object from Service to Component

Currently, I am in the process of developing a login page using Angular for the front-end and Spring Security for the back-end. Everything appears to be functioning correctly, except for handling exceptions when attempting to catch errors from the service ...

Easy way to eliminate empty elements following a class using jQuery

I'm encountering a situation where I have a group of elements following a specific class that are either empty or contain only white space. <div class="post-content"> <div class="slider-1-smart"> --- slider contents --- < ...

AngularJS - Introducing blurred delay

Here is the code snippet I am working with: <div class="staff"> <input ng-model="user" ng-focus="isFocused = true;" ng-blur="isFocused = false;/> <div class="matches" ng-if="isFocused"> <div ...

Finding documents by name in Photoshop

When working with multiple open Photoshop files, the usual method of using getByName for layers or history states doesn't seem to work for documents. var srcDoc = app.Documents.getByName("Gwen_Stefani"); // no success Is this the correct ap ...

Increased/Decreased impact

Can someone explain how the "Tell me more" effect is achieved on the website linked below? I'm familiar with the read more/less effect in jQuery, but what intrigues me is that the page cannot be scrolled unless the button is clicked. Here is the link ...

various types of information in a grid

My data includes the following matrices: [[-0.96092685 1.16253848] [ 1.49414781 0.265738 ] [ 0.02689231 -1.09912591] ... [ 0.16677277 1.43807138] [-0.36808792 -0.03435113] [-0.3693595 0.44464701]] and another matrix like this: [-1 1 -1 -1 -1 ...

Update the sum upon deleting a feature in an HTML and JavaScript form

Once a row or field is added, this function will display a delete link. When clicked, it will remove the row or field: var ct = 1; function addNewRow(){ ct++; var divElement = document.createElement('div'); divElement.id = ct; // Code to cr ...

Error: Python data loading can only convert arrays with a length of 1 to scalars in a dataset

Apologies for my lack of experience within the community. This question may seem simple, but I am struggling with it. I have generated a numpy matrix and now I want to evaluate the density points using the meanshift algorithm. However, I'm encounterin ...

Using a PHP foreach loop to iterate through an array containing both strings and

#1 How do I combine the following code: $enderecofoto = $xml->imovel[$i]->fotos->foto; $nomeeextensao = preg_replace("(^.*\/(.*)\$)", "$1$2",$enderecofoto); $removenomeeextensao = str_replace($nomeeextensao, "", $enderecofoto); $nomefo ...

Using Jquery to iterate through a PHP array, calling an API to fetch data, and then storing the results

I am working with a PHP array called startups[] that contains 36000 startup names. My goal is to create a URL API endpoint using these names. Despite my efforts, I have been unsuccessful in utilizing jQuery to iterate through this PHP array and for each o ...

Is it possible to populate the bit fields of a struct using an unsigned character array in C++?

My challenge lies in populating the fields of a struct with values from an unsigned char array. The array has the following values: u_char *t_header[4]; //filled with values 0x00000047,0x00000004,0x00000093,0x00000012 Here is the struct I am working with ...

Having trouble scrolling with Selenium WebDriver and JavaScript Executor

Can you help me locate and click on the 5th element in this list? The following is a list of all the rooms stored: @FindBy(xpath="//p[@class='css-6v9gpl-Text eczcs4p0']") List<WebElement> placeListings; Code to click on t ...

Fetching dynamic information via AJAX for a jQuery tooltip

I have successfully loaded content via AJAX, including a UL element with li items that each have tooltips. Now I want to load tooltip content via AJAX for each individual li item. How can I achieve this? Currently, I am making an AJAX call to load the li ...

Node.js Export Module Error - importance of separating concerns

I have been attempting to implement separation of concerns by using export module. Everything functions properly when used without separating concerns, but as soon as I try to import generateUrlArray() from const db = require('../db'), nothing se ...

Accessing website login - <div> and validating user entry

I am currently working on developing a basic login webpage, but I am facing issues with the rendering of the page. Below is the code I am using: function logIn(username, password){ var username = document.getElementById("username").value; var p ...

How to use jQuery to locate and update the final parameter of a URL

Hello everyone, I've already done some research but couldn't find a solution that fits my needs. Can anyone assist me with this? I currently have a URL "/view/album/4/photo/1" and I am looking to remove the final parameter and replace it with so ...

Can a Set (or Map) be held in a "frozen" state?

Despite the fact that Set is an Object, Object.freeze() specifically operates on the properties of the object, a feature not utilized by Map and Set: for example let m = new Map(); Object.freeze(m); m.set('key', 55); m.get('key'); // == ...

"Textarea auto-resizing feature causes an excessive number of unnecessary lines to be added

I have a textarea that is coded with jQuery to limit the characters to 11 per line and automatically resize based on the number of lines. However, when users click 'Enter' to add a new line, it adds multiple extra lines instead of just one. This ...