views:

6086

answers:

8

I read in the following JSON object using ajax and store the object as 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

+12  A: 

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);
rmarimon
Here's a reference to the built in Array sort method - http://www.w3schools.com/jsref/jsref_sort.asp
Kevin Hakanson
A: 

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 :)

rpflo
A: 

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 much items.
Take a look here (very good actually) and in wikipedia for more info.
Also take a look at the Array.sort() function.

the_drow
-1 Really no need to write your own sort function here..
Tomas
+8  A: 
homes.sort(function(a,b) { return parseFloat(a.price) - parseFloat(b.price) } );
Stobor
Never mind, rmarimon got there first...
Stobor
A: 

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.

Tim Gilbert
A: 

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);
Johnny G
+12  A: 

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){

   reverse = (reverse) ? -1 : 1;

   return function(a,b){

       a = a[field];
       b = b[field];

       if (typeof(primer) != 'undefined'){
           a = primer(a);
           b = primer(b);
       }

       if (a<b) return reverse * -1;
       if (a>b) return reverse * 1;
       return 0;

   }
}

Now you can sort by any field at will

// 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()}));
Triptych
+1: I like that!
Stobor
awesome thanks Triptych
Darcy
A: 

@ Triptych

Not enough reputation to vote, but I gotta thank Triptych 'cos his answer was very helpful. hamen

hamen
Should be a comment on my answer, but thank you!
Triptych