G3TH G3TH - 6 months ago 43
Javascript Question

Javascript 2D array getting each element

New to Javascript here so bare with me please.
I have a 2D array that looks like:

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


I'd like to iterate through the array and take out 'V1.0' and 'V2.0' and store them in their own new array, and do the same for '1' and '2'. I need to break the data up for use with Chart.js

My loop looks like this:

var labels = [];
var data = [];

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

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


I don't know how to properly get either element into their own array for use later. Any help would be appreciated.

Answer Source

You can use map to do this, and shift the result in order to remove the first occurence.

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

var result = example.map(e => e[0])

console.log(result);

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download