0

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.

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
G3TH
  • 247
  • 4
  • 14
  • 1
    Possible duplicate of [For loop in multidimensional javascript array](https://stackoverflow.com/questions/10021847/for-loop-in-multidimensional-javascript-array) – Heretic Monkey Aug 16 '17 at 14:41

3 Answers3

4

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);
Serge K.
  • 5,303
  • 1
  • 20
  • 27
1

From what I saw into your example the first pair of elements are the keys for your data, into your example will include them into your final arrays.

This example will generate to a dictionary with the keys Number and Version containing the corresponding values from your array.

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

function extract(items) {
  var keys = {},
      version = items[0][0],
      number = items[0][1];
  
  keys[version] = [];
  keys[number] = [];
   
  return items.slice(1).reduce(function(acc, item) {
    acc[version].push(item[0]);    
    acc[number].push(item[1]);
    
    return acc;
  }, keys);
}

var result = extract(example);
console.log(result);

From this point you can do something like:

var labels = result.Version;
var data = result.Number;
0

This looks like what you are trying to achieve:

for(var i=0; i<example.length; i++){

  labels.push(example[i][0])
  data.push(example[i][1])
}
jidexl21
  • 609
  • 7
  • 22