Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I read the following JSON using Ajax and stored 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 ascending order, and also be able to sort it in descending ordering using only JavaScript?

share|improve this question

7 Answers

up vote 154 down vote accepted
homes.sort(function(a,b) { return parseFloat(a.price) - parseFloat(b.price) } );
share|improve this answer
4  
Never mind, rmarimon got there first... – Stobor Jun 11 '09 at 4:12
3  
What about a string comparison? – Brig Mar 1 '12 at 19:26
// 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
2  
+1: I like that! – Stobor Jun 11 '09 at 5:17
3  
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
24  
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
2  
A small enhancement: var key = primer ? function (x) { return primer(x[field]); } : function (x) { return x[field]; } – ErikE Aug 7 '12 at 1:18
5  
Here is a working jsfiddle vesrion of this code: jsfiddle.net/dFNva/1 – Blake Mills Jan 17 at 4:32
show 12 more comments

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
For me, sorting ascending went the way that was originally coded: a.price - b.price – dmonopoly Mar 8 at 16:36

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

This is a nice JQuery plug in:

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

share|improve this answer

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

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

Your Answer

 
discard

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