Reputation: 1338
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>
Upvotes: 0
Views: 57
Reputation: 576
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
});
}
Upvotes: 0
Reputation: 3423
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.
Upvotes: 1