PDA

View Full Version : Sorting multidimensional arrays


rokujou
04-12-2007, 10:39 AM
I was hoping someone here might be able to help me understand array sorting a bit better.

Basically, I have a piece of JS code that uses the eBay REST API for searching. Each item returned is converted to an array and added to another array, giving the following format:

searchResults[1stItem]
searchResults[1stItem]["price"]
searchResults[1stItem]["bids"]
searchResults[1stItem]["endtime"]
searchResults[2ndItem]
searchResults[2ndItem]["price"] ... etc

What I want to do is sort the main array by an item in the second level of the array (ie price). Does anyone know how this can be done?

Thanks very much in advance for your help

Andy

glenngv
04-12-2007, 08:57 PM
Try this:
function sortByPriceAsc(a, b){
if (a["price"] < b["price"])
return -1;
else if (a["price"] > b["price"])
return 1;
return 0;
}
...
searchResults.sort(sortByPriceAsc);