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 objects using Ajax and stored them 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 order using only JavaScript?

share|improve this question
add comment

7 Answers

up vote 202 down vote accepted
homes.sort(function(a,b) { return parseFloat(a.price) - parseFloat(b.price) } );
share|improve this answer
8  
Never mind, rmarimon got there first... –  Stobor Jun 11 '09 at 4:12
5  
What about a string comparison? –  Brig Mar 1 '12 at 19:26
add comment
// 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 = primer ? 
       function(x) {return primer(x[field])} : 
       function(x) {return x[field]};

   reverse = [-1, 1][+!!reverse];

   return function (a, b) {
       return a = key(a), b = key(b), reverse * ((a > b) - (b > a));
     } 

}


// 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
3  
+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
26  
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
8  
Here is a working jsfiddle vesrion of this code: jsfiddle.net/dFNva/1 –  Blake Mills Jan 17 at 4:32
show 14 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
add comment

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
add comment

This is a nice JQuery plug in:

http://plugins.jquery.com/project/sort (Wayback Machine Link)

share|improve this answer
 
Link is corrupt –  Lucio Aug 22 at 3:34
add comment

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
add comment

for string sorting in case some one needs it,

var dataArr = {  

    "hello": [{
    "id": 114,
    "keyword": "zzzzzz",
    "region": "Sri Lanka",
    "supportGroup": "administrators",
    "category": "Category2"
}, {
    "id": 115,
    "keyword": "aaaaa",
    "region": "Japan",
    "supportGroup": "developers",
    "category": "Category2"
}]

};
var sortArray = dataArr['hello'];
sortArray.sort(function(a,b) {
    if ( a.region < b.region )
        return -1;
    if ( a.region > b.region )
        return 1;
    return 0;
} );
share|improve this answer
add comment

Your Answer

 
discard

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