0

This is what I currently have.

[
    [
        {"label":"Year","type":"number"},
        {"label":"Value","type":"number"},
    ],
    {"2013" : 70}, 
    {"2014" : 78}, 
    {"2015" : 125}, 
    {"2016" : 153}
]

this is what I am using to generate the above code.

var data = [
    {"Year":2013,"Product":"A","Value":0},
    {"Year":2013,"Product":"B","Value":20},
    {"Year":2013,"Product":"A","Value":50},
    {"Year":2014,"Product":"D","Value":55},
    {"Year":2014,"Product":"M","Value":23},
    {"Year":2015,"Product":"D","Value":73},
    {"Year":2015,"Product":"A","Value":52},
    {"Year":2016,"Product":"B","Value":65},
    {"Year":2016,"Product":"A","Value":88}
];

var sum = data.reduce(function(res, product) {

  if (!(product.Year in res)) {
    res[product.Year] = product.Value;
  } else {
    res[product.Year] += product.Value;
  }
  return res;
}, {});

var result = [];

for (var year in sum) {
  var tmp = {};
  tmp[year] = sum[year];
  result.push(tmp);
}
result.splice(0, 0, [{
  label: 'Year',
  type: 'number'
}, {
  label: 'Value',
  type: 'number'
}]);

and I want to organize them into [Year, Value] pairs instead of objects, like this:

[["Year", "Value"], ["2013", 70], ["2014", 78], ["2015", 125], ["2016", 153]]
9
  • did you mean ["Year","Value"] ... and you want to convert to array only - as the output you seek is NOT an object at all Commented Nov 17, 2016 at 5:06
  • Yes , actually I need this data for google.visualization.arrayToDataTable(); Commented Nov 17, 2016 at 5:10
  • I just edited/update my code to show you how I am generating the data Commented Nov 17, 2016 at 5:37
  • your output requirement is still impossible ... did you mean [["Year","Value"], ["2013" , 70], ["2014", 78], ["2015", 125], ["2016",153]] Commented Nov 17, 2016 at 5:37
  • yes, as I told you I need this data for google.visualization.arrayToDataTable(); if you can give me in any format which the chart accepts then its ok. Commented Nov 17, 2016 at 5:40

1 Answer 1

0

You are pushing objects ({}) into the array. What you want is to use the array brackets instead ([]) in the second line shown below:

for (var year in sum) {
  var tmp = [];
  tmp[year] = sum[year];
  result.push(tmp);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.