3👍
✅
You get the entire data field of the object as second argument, so you can calculate the amount each dataset represents and then check if it is that dataset:
const options = {
type: 'line',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [120, 19, 3, 5, 2, 3],
borderWidth: 1
},
{
label: '# of Points',
data: [7, 11, 5, 8, 3, 7],
borderWidth: 1
},
{
label: '# of Points1',
data: [17, 11, 5, 8, 3, 7],
borderWidth: 1
},
{
label: '# of Points2',
data: [27, 11, 5, 8, 3, 7],
borderWidth: 1
},
{
label: '# of Points3',
data: [37, 11, 5, 8, 3, 7],
borderWidth: 1
},
{
label: '# of Points4',
data: [47, 11, 5, 8, 3, 7],
borderWidth: 1
},
{
label: '# of Points5',
data: [57, 11, 5, 8, 3, 7],
borderWidth: 1
},
{
label: '# of Points6',
data: [67, 11, 5, 8, 3, 7],
borderWidth: 1
},
{
label: '# of Points7',
data: [77, 11, 5, 8, 3, 7],
borderWidth: 1
},
{
label: '# of Points8',
data: [87, 11, 5, 8, 3, 7],
borderWidth: 1
},
{
label: '# of Points9',
data: [97, 11, 5, 8, 3, 7],
borderWidth: 1
}
]
},
options: {
plugins: {
legend: {
labels: {
filter: (ds, data) => {
const sortable = [];
data.datasets.forEach(d => {
sortable.push([d.label, d.data.reduce((a, b) => (a + b), 0)])
});
sortable.sort((a, b) => (b[1] - a[1]));
const sorted = sortable.slice(0, 5).map(e => (e[0]));
return sorted.includes(ds.text)
}
}
}
}
}
}
const ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.0/chart.js"></script>
</body>
Source:stackexchange.com