[英]How to sort div data in descending order
I have a div that shows the percentage of the particular color.我有一个 div 显示特定颜色的百分比。 I want to sort the div percentage in descending order.我想按降序对 div 百分比进行排序。 How to proceed?如何进行? Below is my code下面是我的代码
function displayLegend() {
for (var key in colorVariable1) {
let percentage = (countVariable1[key] / totalPCICount) * 100;
if(percentage) {
percentage = percentage.toFixed(2);
}
var line = document.createElement("div");
line.innerHTML = '<span class="box" style=" background: ' + colorVariable1[key] + ';"></span><span>' + key + '(' + percentage + '%)</span>';
document.getElementById("legendInfo").appendChild(line);
}
}
Below is the image.I want to sort the percentage part.下面是图像。我想对百分比部分进行排序。
You probably need to store your data first in a structured form, to be able to sort it.您可能需要首先以结构化形式存储数据,以便能够对其进行排序。
I've re-written your sample to show my idea - untested.我已经重新编写了您的示例以展示我的想法 - 未经测试。
var values = []; // holder for rows
for (var key in colorVariable1) {
let percentage = (countVariable1[key] / totalPCICount) * 100;
if(percentage) {
percentage = percentage.toFixed(2);
} else {
percentage = 0;
}
// row definition
let entry = {
value: percentage,
html: '<span class="box" style=" background: ' + colorVariable1[key] + ';"></span><span>' + key + '(' + percentage + '%)</span>';
}
values.push(entry); // add row to holder
}
// sort rows in holder by value (percentage)
// see: https://stackoverflow.com/questions/979256/sorting-an-array-of-objects-by-property-values
values.sort(function(a, b) {
return parseFloat(b.value) - parseFloat(a.value);
});
// add sorted lines
for(var i in values){
var line = document.createElement("div");
line.innerHTML = values[i].html;
document.getElementById("legendInfo").appendChild(line);
}
Try this..尝试这个..
// Assummed sample data var colorVariable1 = {302:"red", 156:"green", 89:"blue", 176:"orange"}; var countVariable1 = {302:30, 156:56, 89:71, 176:89}; var totalPCICount = 75; function displayLegend() { var percentages = {}; for (var key in colorVariable1) { let percentage = (countVariable1[key] / totalPCICount) * 100; percentages[key] = percentage.toFixed(2); } var sorted = Object.keys(percentages) .sort(function(a, b) { return (+percentages[a]) - (+percentages[b]) }); for (var key of sorted) { var line = document.createElement("div"); line.innerHTML = '<span class="box" style="background-color:' + colorVariable1[key] + ';"></span><span>' + key + '(' + percentages[key] + '%)</span>'; document.getElementById("legendInfo").appendChild(line); } }
.box { width: 5px; height: 5px; padding: 5px; }
<button onclick="displayLegend()">click</button> <div id="legendInfo"></div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.