I read in the following JSON using Ajax and store the objects in an array:

var homes = [{
   "h_id": "3",
   "city": "Dallas",
   "state": "TX",
   "zip": "75201",
   "price": "162500"
}, {
   "h_id": "4",
   "city": "Bevery Hills",
   "state": "CA",
   "zip": "90210",
   "price": "319250"
}, {
   "h_id": "5",
   "city": "New York",
   "state": "NY",
   "zip": "00010",
   "price": "962500"
}];

How do I create a function to sort the "price" field in ASC and also sort in DESC ordering using only JavaScript?

Thanks in advance

share|improve this question
feedback

9 Answers

up vote 84 down vote accepted
homes.sort(function(a,b) { return parseFloat(a.price) - parseFloat(b.price) } );
share|improve this answer
2  
Never mind, rmarimon got there first... – Stobor Jun 11 '09 at 4:12
1  
What about a string comparison? – Brig Mar 1 at 19:26
feedback
// Here's a more flexible version, which allows you to create 
// reusable sort functions, and sort by any field

var sort_by = function(field, reverse, primer){

   var key = function (x) {return primer ? primer(x[field]) : x[field]};

   return function (a,b) {
       var A = key(a), B = key(b);
       return ((A < B) ? -1 :
               (A > B) ? +1 : 0)) * [-1,1][+!!reverse];                  
   }
}


// Now you can sort by any field at will...

var homes = [{
   "h_id": "3",
   "city": "Dallas",
   "state": "TX",
   "zip": "75201",
   "price": "162500"
}, {
   "h_id": "4",
   "city": "Bevery Hills",
   "state": "CA",
   "zip": "90210",
   "price": "319250"
}, {
   "h_id": "5",
   "city": "New York",
   "state": "NY",
   "zip": "00010",
   "price": "962500"
}];

// Sort by price high to low
homes.sort(sort_by('price', true, parseInt));

// Sort by city, case-insensitive, A-Z
homes.sort(sort_by('city', false, function(a){return a.toUpperCase()}));
share|improve this answer
1  
+1: I like that! – Stobor Jun 11 '09 at 5:17
awesome thanks Triptych – Darcy Oct 1 '10 at 18:03
1  
nickb - you're misreading the code. sort_by runs in O(1), and returns a function used by the built-in sort (O(N log N)) to compare items in a list. The total complexity is O(n log n) * O(1) which reduces to O(n log n), or the same as a quick sort. – Triptych Oct 31 '11 at 7:04
15  
Excellent idea! A few issues: 1-A left parenthesis seems to be in the wrong place. 2-Setting the reverse looks reverse :) 3-Line break seems to cause issues. Overall, shouldn't that one-liner be return (A < B ? -1 : (A > B ? 1 : 0)) * [1,-1][+!!reverse]; ? – Halil Özgür Dec 9 '11 at 15:52
1  
A small enhancement: var key = primer ? function (x) { return primer(x[field]); } : function (x) { return x[field]; } – ErikE Aug 7 at 1:18
show 9 more comments
feedback

To sort it you need to create a comparator function taking two arguments and then call the sort function with that comparator function as follows:

// a and be are object elements of your array
function mycomparator(a,b) {
  return parseInt(a.price) - parseInt(b.price);

}

If you want to sort ascending change parseInt(a.price) - parseInt(b.price) to parseInt(b.price) - parseInt(a.price). Note the change from a to b.

To do the sort

homes.sort(mycomparator);
share|improve this answer
2  
Here's a reference to the built in Array sort method - w3schools.com/jsref/jsref_sort.asp – Kevin Hakanson Jun 11 '09 at 4:17
feedback

You want to sort it in Javascript, right? What you want is the sort() function. In this case you need to write a comparator function and pass it to sort(), so something like this:

function comparator(a, b) {
    return parseInt(a["price"]) > parseInt(b["price"]);
}

var json = { "homes": [ /* your previous data */ ] };
console.log(json["homes"].sort(comparator));

Your comparator takes one of each of the nested hashes inside the array and decides which one is higher by checking the "price" field.

share|improve this answer
feedback

This is a nice JQuery plug in:

http://plugins.jquery.com/project/sort

share|improve this answer
feedback

You can use the JavaScript sort method with a callback function:

function compareASC(homeA, homeB)
{
    return parseFloat(homeA.price) - parseFloat(homeB.price);
}

function compareDESC(homeA, homeB)
{
    return parseFloat(homeB.price) - parseFloat(homeA.price);
}

// Sort ASC
homes.sort(compareASC);

// Sort DESC
homes.sort(compareDESC);
share|improve this answer
feedback

You can find more plugins using following URL.. http://tympanus.net/codrops/2009/10/03/33-javascript-solutions-for-sorting-tables/

share|improve this answer
feedback

Since objects don't really have an order I'm not aware of any functions to re-order them.

Of course, I don't know everything. Maybe you ought to store that stuff in an array instead? You can still pass it around like an object.

Edit:

Didn't pay enough attention to the code, that was an array in the first place, not an object. Ignore this post :)

share|improve this answer
feedback

Do you know bubble sort or quick sort?
This is a normal array as all arrays are and you can sort them using the known algorithm.
Bubble sort seems the most appropriate since you don't have many items.
Take a look here (very good actually) and in wikipedia for more info.
Also take a look at the Array.sort() function.

share|improve this answer
3  
-1 Really no need to write your own sort function here.. – Tomas Dec 29 '09 at 12:41
feedback

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.