将数组值转换为百分比Javascript [duplicate]

mzmfm0qo  于 2023-02-11  发布在  Java
关注(0)|答案(2)|浏览(131)
    • 此问题在此处已有答案**:

How to get a percentage of total when the query has a GROUP BY?(5个答案)
17小时前关门了。
我有一个饼图,它引用数组中的值。
我想把这些数组值显示为百分比。我该怎么做?
我用来生成此饼图的插件是chart.js
Javascript供参考:

success : function (data){
    console.log(data);

    var categoryname = ["Drain", "Building", "Pest", "Broken Utilities", 
    "Littering", "Leakage", "Lighting"];
    var category = [];
    var amount = [];

    for (var i in data) { 
        category.push(categoryname[data[i].Category]);
        amount.push (data[i].CaseNum);
    }
    var config = {
        type: 'pie',
        data: {
            datasets: [{
                data: amount,
                backgroundColor: [
                    "rgba(59, 89, 152, 1)",
                    "rgba(59, 89, 152, 1)",
                    "rgba(59, 89, 152, 1)",
                    "rgba(59, 89, 152, 1)",
                    "rgba(59, 89, 152, 1)",
                    "rgba(59, 89, 152, 1)",
                    "rgba(59, 89, 152, 1)"
                    ],
                label: 'Dataset 1'
            }],
                labels: category
        },
        options: {
            responsive: true
        }
    };
    var ctx = $("#mycanvas");       
    var graph = new Chart(ctx, config);
}

Php供参考:

$query = "SELECT categoryID as 'Category', COUNT(Case.categoryID) as 'CaseNum' 
FROM `Case` WHERE CaseTime BETWEEN DATE_SUB(now(), INTERVAL 6 MONTH) AND 
now() GROUP BY categoryID ORDER BY categoryID";

$result = $conn->query($query);

$data = array();
foreach ($result as $row) {
    $data[] = $row;
}

$conn->close();

print json_encode($data);

Piechart图像示例:

nqwrtyyt

nqwrtyyt1#

试试这个

success : function (data){
    console.log(data);

    var integerAmount = [];
    for (var i in data) {
        integerAmount.push(data[i].CaseNum);
    }
    var sum = integerAmount.reduce((a, b) => a + b, 0);
    var categoryname = ["Drain", "Building", "Pest", "Broken Utilities", "Littering", "Leakage", "Lighting"];
    var category = [];
    var amount = [];
    for (var i in data) {
        category.push(categoryname[data[i].Category]);
        amount.push (integerAmount[i]/sum*100+'%');
    }

    // rest of the script
}

我们的想法是先存储data对象中的Integers值,然后对总值求和,最后推送实际百分比值,并将%添加到amount数据中以生成饼图。

x6yk4ghg

x6yk4ghg2#

如果你有一个数字数组,那么它就像把数组减少到一个和,然后Map每个元素以除以这个和一样简单。

let a = [123,32,22,23,64]
let sum = a.reduce((a,b) => a+b)
let a_percentage = a.map(e => e/sum*100)

然后可以根据需要设置其格式。

相关问题