I have an AJAX call returning JSON like...
{
490: "A",
675: "B",
491: "C",
520: "D",
681: "E",
679: "F",
538: "G"
}
I then have it appending to a select
using:
var output = jQuery.parseJSON(data);
$.each(output, function(key, value) {
$el.append($("<option></option>")
.attr("value", key).text(value));
});
I'd like to sort by the value so the output is A,B,C,D...
as right now it just reads in order of the key.
Here's the kicker - seems to work fine in Firefox, not in Chrome.
To sort an array of objects, you use the sort() method and provide a comparison function that determines the order of objects.
JavaScript Array sort() The sort() sorts the elements of an array. The sort() overwrites the original array. The sort() sorts the elements as strings in alphabetical and ascending order.
sort() method is used to sort the array elements in-place and returns the sorted array. This function sorts the elements in string format. It will work good for string array but not for numbers. For example: if numbers are sorted as string, than “75” is bigger than “200”.
first convert it into array, sort it, then create html. jsfiddle
var output = jQuery.parseJSON(data);
var temp = [];
$.each(output, 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(key, obj) {
$el.append($("<option></option>")
.attr("value", obj.k).text(obj.v));
});
Objects cannot be sorted. Try returning your JSON as an array to ensure it stays in the exact order that you return them in:
[
{"id":490,"name":"A"},
{"id":675,"name":"B"},
{"id":491,"name":"C"},
{"id":520,"name":"D"},
{"id":681,"name":"E"},
{"id":679,"name":"F"},
{"id":538,"name":"G"}
]
Here's a fiddle with the original: http://jsfiddle.net/82BSm/2/ and changing to an array: http://jsfiddle.net/82BSm/1/
Updated per pst's comment
You could of course make the json response size smaller by separating the column names ("id" and "name") from the data and making it an array of arrays.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With