Reputation: 315
I have the JSON look like below. I'm finding the way to sort the numberOfPoint after I summed up.
{ "data": [
{
"id": {
"year": 2015,
"Name": "A"
},
"numberOfPoint": 2
},
{
"id": {
"year": 2014,
"Name": "C"
},
"numberOfPoint": 2
},
{
"id": {
"year": 2014,
"Name": "B"
},
"numberOfPoint": 2
},
{
"id": {
"year": 2014,
"Name": "B"
},
"numberOfPoint": 2
},
{
"id": {
"year": 2013,
"Name": "C"
},
"numberOfPoint": 2
}]
}
obj is my JSON.
var result = {};
obj.data.forEach(function (a) { result[a["id"]["Name"]] = (result[a["id"]["Name"]] || 0) + a["numberOfPoint"]; });
result is look like below
{
"A": 2,
"C": 4,
"B": 4
}
How can I sort this from largest to lowest numberOfPoint? I want the result like this.
{
"B": 4,
"C": 4,
"A": 2
}
Thank you in advance.
Upvotes: 1
Views: 93
Reputation: 336
var obj = { "data": [ { "id": { "year": 2015, "Name": "A" }, "numberOfPoint": 2 }, { "id": { "year": 2014, "Name": "C" }, "numberOfPoint": 2 }, { "id": { "year": 2014, "Name": "B" }, "numberOfPoint": 2 }, { "id": { "year": 2014, "Name": "B" }, "numberOfPoint": 2 }, { "id": { "year": 2013, "Name": "C" }, "numberOfPoint": 2 }] } var result = {}; obj.data.forEach(function (a) { result[a["id"]["Name"]] = (result[a["id"]["Name"]] || 0) + a["numberOfPoint"]; }); var temp = []; $.each(result, function(key, value) { temp.push({v:value, k: key}); }); temp.sort(function(a,b){ if(a.v < b.v){ return 1} if(a.v > b.v){ return -1} return 0; }); $.each(temp, function(index, obj) { alert(obj.k + "-" + obj.v); });
I hope you like this..if you like then don't forget to vote me..and thanks @Butani Vijay for nice sorting. i have implemented in common...
Upvotes: 1
Reputation: 4239
You can do as below :
var result={
"A": 2,
"C": 4,
"B": 4,
"D": 3
}
var temp = [];
$.each(result, function(key, value) {
temp.push({v:value, k: key});
});
temp.sort(function(a,b){
if(a.v < b.v){ return 1}
if(a.v > b.v){ return -1}
return 0;
});
$.each(temp, function(index, obj) {
alert(obj.k + "-" + obj.v);
});
Upvotes: 1
Reputation: 241
Maybe this will help.
obj.data.sort(function(a, b) {
return a.id.Name < b.id.Name;
});
for(var i in obj.data) {
console.log(obj.data[i].id.Name);
}
Upvotes: 1