0

I was wondering if someone could help me get this to work so it prints out values and sorts them by propertyCount, highest to lowest. Below gets me the the first 6 values from a JSON file.

Basically, Im trying to only grab 6 values from a JSON file where it's sorted by a key called count that has a number value. Any help is greatly appreciated.

var countyInfo = [];
var count = 0;
var propertyCount = 0;

function getCountyInfo($j) {
  //$j.ajax({
  //  url: "/info.json?st=WA"
  //}).done(function(data) {
    //countyInfo = data;
    countyInfo = getDataDemo();
    $j.each(countyInfo.counts.county_info, function(key, value) {

      $j.each(value, function(key, value) {

        if (key == "count") {
          propertyCount = value;
        }

        if (key == "countyName" && value != null) {
          var countyName = value;
          if (count < 6) {
            $j('#countyList').append('<li class="topCountyRow">' + countyName + ' (' + propertyCount + ')</li>');
          }
          count++;
        }
      });
    });
  //});

}

(function($j) {
  //loaded();
  var county_info = [];
  getCountyInfo($j);
})(jQuery);

// Just for the StackOverflow Question
function getDataDemo() {
  return JSON.parse(`{
    "state": "wa",
    "stateName": "Washington",
    "counts": {
      "county_info": [
        {
        "count": 72,
        "countyName": "Anderson"
        },
        {
        "count": 43,
        "countyName": "Angelina"
        }
      ]
    }
  }`);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<ul id="countyList" class="ulTwoColumns"></ul>

2
  • what does the data object look like? Is it an object or an array? Commented Mar 12, 2019 at 21:20
  • I updated with a sample of what JSON looks like. Commented Mar 12, 2019 at 21:37

2 Answers 2

1

You can use sort function of array where you need to pass comparer function as below.

function sort(data)
{
    return  data.counts.county_info.sort((left,right)=>{
    return left.count<right.count?1:-1;
  })
}

Updated as per your data.

Sign up to request clarification or add additional context in comments.

Comments

0

Use the sort method to compare and sort

data.counts.county_info.sort(a, b => a.count < b.count);

Implementing in your code above

function getCountyInfo(){
    $j.ajax({
        url: "/info.json?st=WA"
    }).done(function(data) {        
        let sortedData = data.counts.county_info.sort(a, b => a.count < b.count);
         // other things to do
    });
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.