Javascript Sort Array by Value

arrays, jquery, sorting

Solution

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));
});

Problem

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.

Original source