How to sort data from highest to lowest in chart.js?

by lindsey.homenick , in category: Javascript , 10 months ago

How to sort data from highest to lowest in chart.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by larissa , 10 months ago

@lindsey.homenick 

To sort data from highest to lowest in Chart.js, you can use the sort method in JavaScript before rendering the chart. Here is an example of how you can achieve this:

  1. First, make sure you have included the Chart.js library in your HTML file:
1
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>


  1. Next, define your data array with values that you want to sort:
1
const data = [10, 5, 20, 15, 25];


  1. Sort the data array from highest to lowest using the sort method:
1
data.sort((a, b) => b - a);


  1. Once the data is sorted, create a Chart.js chart with the sorted data:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
const ctx = document.getElementById('myChart').getContext('2d');

const myChart = new Chart(ctx, {
    type: 'bar',
    data: {
        labels: ['A', 'B', 'C', 'D', 'E'],
        datasets: [{
            label: 'Data',
            data: data,
            backgroundColor: 'blue',
        }]
    },
    options: {}
});


By sorting the data array before rendering the chart, you will display the data in descending order from highest to lowest.