Neal Jones
Neal Jones

Reputation: 459

Concatenating objects to use for a chart

This seems like it should be simple but I have been working on this and am still stumped. Here is a Codepen link to what I have so far.

I need to allow the user select a data set (via a button) and then add that data set to whatever other data sets have already been selected up to that time, there would not be more than 3 or 4 data sets. My code right now looks like this:

HTML:

<button onclick="createDataSet(data1);">Add Data 1</button>
<button onclick="createDataSet(data2);">Add Data 2</button>

<button onclick="makeChart();">Make Chart</button>

JS:

var data1 = [{...},{...}];
var data2 = [{...},{...}];

// function is supposed to create a new concatenated dataset 
function createDataSet(data) {
  var dataSet = [];
  dataSet = dataSet.push(data);
  console.log(dataSet);
  return dataSet;
};

function makeChart(chartData){
  LoadChart(chartData);
}

// will make the following functional later
function LoadChart(){
  console.log("chart is made");
}

I have tried using concat() for this like the following:

function createDataSet(data) {
  var temp = [];
  var dataSet = [];
  temp = dataSet.concat(data);
  console.log(temp);
  return dataSet;
};

but that didn't work as well, I expect my approach is fundamentally flawed somehow right now. Again, here is a Codepen link to what I have so far.

Thanks for reading!

Upvotes: 1

Views: 31

Answers (1)

Yosvel Quintero
Yosvel Quintero

Reputation: 19080

You can use Array.prototype.concat() to concatenate arrays to the array variable dataSet:

var data1 = [{"fake": 2132,"data": 2676,"example": "human"}, {"fake": 2132,"data": 2676,"example": "human"}, {"fake": 2132,"data": 2676,"example": "human"}, {"fake": 2132,"data": 2676,"example": "human"}, {"fake": 2132,"data": 2676,"example": "human"}, {"fake": 2132,"data": 2676,"example": "human"}, {"fake": 2132,"data": 2676,"example": "human"}],
    data2 = [{"fake": 32,"data": 76,"example": "human"}, {"fake": 32,"data": 76,"example": "human"}, {"fake": 32,"data": 76,"example": "human"}, {"fake": 32,"data": 76,"example": "human"}, {"fake": 32,"data": 76,"example": "human"}, {"fake": 32,"data": 76,"example": "human"}, {"fake": 32,"data": 76,"example": "human"}],
    dataSet = [];

function createDataSet(data) {
  dataSet = dataSet.concat(data);
}

function makeChart(dataSet){
  console.log(dataSet);
  LoadChart(dataSet);
}

// will make the following functional later
function LoadChart(){
  console.log("chart is made");
}
<button onclick="createDataSet(data1);">Add Data 1</button>
<button onclick="createDataSet(data2);">Add Data 2</button>

<button onclick="makeChart(dataSet);">Make Chart</button>

Upvotes: 1

Related Questions