Retrieving individual elements from a 2D array in Javascript

I am working with a 2D array that's structured like this:

var data = [['Version', 'Number'], [ 'V1.0', 1 ], [ 'V2.0', 2 ]];

My goal is to parse through the array and extract 'V1.0' and 'V2.0' into a new array, as well as '1' and '2'. This separation is needed for integration with Chart.js

The loop I am currently using is as follows:

var versionLabels = [];
var numberData = [];

for (var i=0; i<data.length; i++) {
    versionLabels.push(data[i][0]);
}

for (var j=0; j<example.length; j++) {
    numberData.push(data[j][1]);
}

I'm struggling with properly segregating each element into their respective arrays for future use.

Answer №1

If you want to achieve this, you have the option of utilizing map and then using shift function to eliminate the initial occurrence.

var sample = [
  ['Theme', 'ID'],
  ['T1', 01],
  ['T2', 02]
];

var outcome = sample.map(e => e[0])

console.log(outcome);

Answer №2

Upon reviewing your example, it appears that the first pair of elements serve as keys for your data. Incorporating them into your final arrays is crucial.

The outcome of this example would be a dictionary with keys 'Number' and 'Version', each containing corresponding values from your array.

var example = [['Version', 'Number'], [ 'V1.0', 1 ], [ 'V2.0', 2 ]];

function transform(data) {
  var keys = {},
      versionKey = data[0][0],
      numberKey = data[0][1];
  
  keys[versionKey] = [];
  keys[numberKey] = [];
   
  return data.slice(1).reduce(function(acc, item) {
    acc[versionKey].push(item[0]);    
    acc[numberKey].push(item[1]);
    
    return acc;
  }, keys);
}

var output = transform(example);
console.log(output);

You can proceed by:

var labels = output.Version;
var information = output.Number;

Answer №3

It appears that this code snippet aligns with your desired outcome:

for(let j=0; j<samples.length; j++){
  
  values.push(samples[j][0]);
  results.push(samples[j][1]);
}

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

What is the best way to horizontally align my divs and ensure they stack properly using media queries?

My layout is not working as expected - I want these two elements to be side by side in the center before a media query, and then stack on top of each other when it hits. But for some reason, it's not behaving the way I intended. I've tried to ce ...

Parsley.js now supports the use of the attribute `data-parsley-errors

Currently, I am attempting to integrate the errors container (e.g., data-parsley-errors-container="#ErrorSummary") with parsley.js. Most aspects are functioning properly, but I've encountered an issue. Specifically, I am looking to solely adjust the ...

Customize Your Google Maps with Checkboxes for Style Options

Trying to make dynamic changes in the style of a Google Maps using checkboxes. Some checkboxes control colors of features, while others control visibility. Having trouble figuring out how to combine different features of styles since they are not strings ...

Switching between various dropdown options does not produce any noticeable differences in the (React) interface

I am experiencing an issue with my dropdown menu where selecting different values no longer triggers any changes. This was working perfectly fine before. Below is the code I am using: context.js: import React, { useState, useEffect } from 'react&apo ...

What's the best way to use JavaScript to obtain the width of a 'css-pixel' based on a media query?

While there have been discussions on how to determine device sizes using media queries like Twitter Bootstrap, I am looking for a reliable way to achieve the same output using JavaScript. Specifically, I want to get the CSS media query pixel number rather ...

What is the best way to delete only the current occurrence of the array, without removing all other instances?

Is there a way to remove only the current instance of the array, without affecting all other instances? var persons = []; showAllButton.onclick = function() { while (showList.firstChild) showList.removeChild(showList.firstChild); New node instances h ...

Issue: ENOENT - The requested file or directory cannot be found in the context of an Angular2 and Express.js

I have made some changes to the Angular2 app on GitHub in order to use Express.js instead of KOA. However, when I try to load the app in FireFox, I encounter the following error in the `nodemon` console: Error: ENOENT: no such file or directory The Angul ...

What is the method for printing a webpage that has been modified using JavaScript?

Take a look at this screenshot to see what I'm working with. Users have the ability to modify the page by removing items, adding new items, or marking items as complete by crossing them out. I want users to be able to print the altered page using Jav ...

Is it possible to store a randomly generated variable in JavaScript for future reference?

Currently, I am involved in a project that involves generating random variables to create unique scenes. One specific variable is the location of these scenes. My goal is to be able to generate a location with just one button click. Subsequently, by pressi ...

Dynamically shift the table footer to the bottom of a scrolling div by utilizing jQuery

I'm facing a challenge where I need to relocate each th tag from the footer row of a table to the bottom of a scrolling div. You can check out the scenario on this link. Currently, I am able to achieve this by hardcoding it like so: $('.sticky- ...

Unveiling Parameters from a Function Transferred as an Argument to Another Function in JavaScript

I'm just getting started with JavaScript and I've encountered a small program where a function takes another function as an argument. My goal is to figure out how to extract or access the arguments of that passed in function. Here's a specif ...

Using the preselection feature in the MUI DataGrid can cause the grid to become disabled

I am customizing a mui datagrid to have preselected rows using the following code snippet: const movieCrewList = movieCrew.map((item) => item.id); const [selecteTabledData, setSelectedTableData] = React.useState([]); <DataGrid rows={crewData} c ...

In Safari, non-ascii characters are incorrectly stored in document.cookies as trash

Below is a snippet of JavaScript code that I am working with: wdata['account'] = {"value": $(input).val(), "title": "Номер карты получения"}; var r = { "ipayway": ipw_selected, "wpayway": wpw_selected, "amount_type" ...

Combining the power of Angular with a Vanilla JS web application

Seeking your expertise. Situation We are transitioning from a legacy Vanilla JS webapp to Angular. Our plan is to gradually replace isolated components while adding new functionality as separate Angular apps, all within a timeframe of 6-12 months. Challe ...

WebDriver encounters difficulty clicking on a certificate error popup window

Currently, I am using webdriver 2.40.0 in C# to interact with my company's website. The issue arises when I encounter a certificate error page while trying to access certain elements. Specifically, after clicking the override link and entering some in ...

Function $locationChangeStart in AngularJS not triggering

My code using the $location service in angular seems to be malfunctioning. angular.module("app",[]).run(function($rootScope) { var $offFunction = $rootScope.$on("$locationChangeStart", function(e) { if (confirm("Are you sure")) return $ ...

Error encountered while integrating sweetalert into Vue.js framework

Can anyone help me with importing sweetalert2 correctly to use Swal in this file only? I tried using <script src = "https://cdn.jsdelivr.net/npm/sweetalert2@9"> but it's not working as expected. What could be the issue? <script ...

Loading SVGs on the fly with Vue3 and Vite

Currently, I am in the process of transitioning my Vue2/Webpack application to Vue3/Vite. Here's an example of what works in Vue2/Webpack: <div v-html="require('!!html-loader!../../assets/icons/' + this.icon + '.svg')" ...

Changing a millisecond date string into a human-readable date format using jQuery

Seeking a way to transform milliseconds into a readable date format, I encountered a roadblock. Despite my extensive search for a solution, none of them seem to address my issue. I'm aiming to make val.start display as 10.15, but it currently shows: ...

Issue: TableHead inside an Expandable Row in MUI-Datatable is being duplicated for each row, causing the table to not be centered.Explanation: The

Can anyone help me with this issue? I'm having trouble with my table where the headings are repeating for every row and the table is stuck on the far right side. How can I center the table instead? https://i.sstatic.net/y7Cs5.png Codesandbox: https: ...