How to add conditional logic on Chart.js config?

👍:-1

From a brief look at Chart.js, it seems that you can use arbitrary JavaScript with it, and a built-in JS feature that fits this situation perfectly is the built-in .filter method of Arrays.

This demo code gives a brief rundown of how it can work for you:

const demo_datasets = [
  {data: "data_1", YAxisID: "data_1-axis"}, // (Has a valid YAxisID)
  {data: "bad_data_1", YAxisID: ""},
  {data: "bad_data_2", YAxisID: 42},
  {data: "bad_data_3" }  
];

// This is how you would populate your actual `datasets` variable. (Initializing 
//   Array w/ spread operator is redundant if demo_datasets is already an Array)
const filtered = filterData([...demo_datasets], hasYAxis);

console.log(`datasets before filtering: ${demo_datasets.length}`);
console.log(`after filtering: ${filtered.length}`)
console.log("\nvalid sets:"); console.log(filtered);


// `filterData` is our main Function
function filterData(dubiousData, filterFunc){
  // `filterData` takes an Array and a Func, uses `.filter` to make a new Array,
  //    which includes only those elements for which Func returns true
  return dubiousData.filter(filterFunc);
}

function hasYAxis(dSet){
  // One possible filter function -- YAxisID must be a non-empty string
  if (dSet.YAxisID && typeof dSet.YAxisID === 'string'){ 
    return true;
  }
}

Leave a comment