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.

1

3 Answers 3

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);

Sign up to request clarification or add additional context in comments.

Comments

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;

1 Comment

I like this answer. I gave the one above the accepted answer because its simpler.
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])
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.