Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Sort Array by Value

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.

like image 389
Fluidbyte Avatar asked Oct 19 '12 20:10

Fluidbyte


People also ask

How do you sort an array by object value?

To sort an array of objects, you use the sort() method and provide a comparison function that determines the order of objects.

Can you sort an array in JavaScript?

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.

How do you sort numbers in an array?

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”.


Video Answer


2 Answers

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));
});
like image 177
Anoop Avatar answered Sep 29 '22 13:09

Anoop


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.

like image 24
Kevin B Avatar answered Sep 29 '22 13:09

Kevin B