因此,我有一个带有Piechart的前端,希望显示我的客户中年龄的百分比(一个数据库表).我已经存储了每个客户的年龄,所以我有一个这样的array.
const ages = [12,42,23,42,12,65,75,12,43,54,12,53,24,23,54,64,76,12,42];
考虑到这些值,我想最终得到这样的东西
const data = {
labels: ['12-20', '21-40', '41-60', '61-76']
dataSet: [4, 6, 2, 5] // This is the amount of ages between each range. The sum of these must be equivalent of the length of the array
}
这就是我到目前为止所try 的
const ages = [12, 42, 53, 12, 32, 12, 52, 66, 76, 87, 23, 12, 43, 12, 43, 54, 65].sort((a, b) => a - b);
const minAge = Math.min(...ages);
const maxAge = Math.max(...ages);
const q1 = ages[Math.floor(ages.length / 4)];
const q2 = ages[Math.floor(ages.length / 2)];
const q3 = ages[Math.floor(ages.length * 3 / 4)];
let firstRangeCount = 0;
let secondRangeCount = 0;
let thirdRangeCount = 0;
let fourthRangeCount = 0;
for (const age of ages) {
if (age) {
if (age <= q1) {
firstRangeCount++;
} else if (age <= q2) {
secondRangeCount++;
} else if (age <= q3) {
thirdRangeCount++;
} else {
fourthRangeCount++;
}
}
}
const data = {
labels: [
`${minAge} - ${q1}`,
`${q1} - ${q2}`,
`${q2} - ${q3}`,
`${q3} - ${maxAge}`,
],
datasets: {
label: 'Ages',
data: [firstRangeCount, secondRangeCount, thirdRangeCount, fourthRangeCount],
}
}
但是这个解决方案的问题是它不是动态的.如果ages数组包含较少的数据,则不适用4个范围.
我怎样才能使这个范围"动态"?.我读过一些关于四分位范围的文章,但对我帮助不大