0

I have a div that shows the percentage of the particular color. I want to sort the div percentage in descending order. 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.

enter image description here


Nirali Biniwale
  • 627
  • 5
  • 16
Priyanka
  • 67
  • 1
  • 8

2 Answers2

1

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);    
}
ihkawiss
  • 986
  • 3
  • 9
  • 25
1

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>
hbamithkumara
  • 2,344
  • 1
  • 17
  • 17