Emil Olsen
Emil Olsen

Reputation: 352

ChartJS combine two arrays with some similarities in one plot

i need to combine two arrays into one barplot without manual manipulation of the arrays. Example of arrays:

result1 = {a:2,b:5,c:52}
result2 = {a:4,b:3,d:47}
//WHERE (to elaborate):
result1.labels = {a, b, c};
result1.data = {2, 5, 52};
result2.labels = {a, b, d};
result2.data = {4, 3, 47};


      var myChart = new Chart(ctx, {
    type: 'bar',
      data: {
          datasets: [{
              label: 'Dataset 1',
              data: result1.data,
              order: 1,
              labels: result1.labels
          }, {
              label: 'Dataset 2',
              data: result2.data,
              order: 2,
              labels: result2.labels
          }]
      },
      options: {
          scales: {
              y: {
                  beginAtZero: true
              }
          }
      }
  });

Right now i will just get 3 stacks of bars where it will merge the 3. entry of result1 and result2, but i need it to make 4 bars "a, b, c, d". I know i can manually fill into result1 and add "d:0" and to result2 add "c:0" but as it is getting the data from a database that constantly changes the returned array size, that is not a good solution.

Thanks

Upvotes: 0

Views: 290

Answers (1)

Reyno
Reyno

Reputation: 6525

You can create a set of all keys and then loop over the object and check if the key already exists. If not add it.

const result1 = {a:2,b:5,c:52};
const result2 = {a:4,b:3,d:47};

const getUniqueKeys = (...objs) => {
  // Create a set of all unique keys
  const keys = objs.reduce((keys, obj) => {
    for(key in obj) {
      keys.add(key)
    }
    
    return keys;
  }, new Set());
  
  // Convert set to array
  return [...keys];
}

const addMissingValues = (keys, obj, fill = 0) => {
  // Create copy to prevent changing the original object
  const copy = {...obj};
  
  for(const key of keys) {
    // Add key if it doesn't exist
    if(!copy.hasOwnProperty(key)) {
      copy[key] = fill;
    }
  }
  
  // Return copy
  return copy;
}

const keys = getUniqueKeys(result1, result2);
const correct1 = addMissingValues(keys, result1);
const correct2 = addMissingValues(keys, result2);

console.log(correct1);
console.log(correct2);

Upvotes: 0

Related Questions