我正在创建条形图,获取月份的数据,它工作得很好,但是顺序从来不是按月份的顺序排列的,而且在每个呈现中都是混乱的。
我从API收到的数据如下:
{
{
"_id": 2022,
"sales": [
{
"month": "Dic",
"year": 2022,
"total": 8737.6
},
{
"month": "Oct",
"year": 2022,
"total": 1936.0000000000002
},
{
"month": "Sep",
"year": 2022,
"total": 526.8000000000001
},
{
"month": "Nov",
"year": 2022,
"total": 2205.2000000000003
}
]
}
}因此,我将这个代码与rep-chartjs-2 (chartjs)一起使用,如下所示:
const data = {
labels: dataOfSalesPerMonth?.map((data) => data.month),
datasets: [
{
label: "Venta Mensual",
data: dataOfSalesPerMonth?.map((data) => data.total),
backgroundColor: [
"rgba(75,192,192,1)",
"#ecf0f1",
"#50AF95",
"#f3ba2f",
"#2a71d0",
],
borderColor: "black",
borderWidth: 2,
},
]
}我的反应是这样的:
return (
<div className="w-full h-44">
{
Object.entries(sales).length &&
<Bar
data={data}
options={options}
/>
}
</div>
)但是这个顺序是不对的,它总是给我混乱的月份,而不是以相同的顺序:

我怎么点呢?谢谢。
发布于 2022-12-03 05:46:03
添加自定义排序逻辑
const data = {
"_id": 2022,
"sales": [
{
"month": "Dic",
"year": 2022,
"total": 8737.6
},
{
"month": "Oct",
"year": 2022,
"total": 1936.0000000000002
},
{
"month": "Sep",
"year": 2022,
"total": 526.8000000000001
},
{
"month": "Nov",
"year": 2022,
"total": 2205.2000000000003
}
]
}
const sortByMonth = (arr) => {
const months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dic"];
arr.sort((a, b)=>{
return months.indexOf(a.month)
- months.indexOf(b.month);
});
}
sortByMonth(data.sales);
console.log(data.sales);
https://stackoverflow.com/questions/74664274
复制相似问题