Skip to content

Instantly share code, notes, and snippets.

@ethyde
Created September 30, 2014 11:05
Show Gist options
  • Save ethyde/6a519f3fcec94c3cb6ec to your computer and use it in GitHub Desktop.
Save ethyde/6a519f3fcec94c3cb6ec to your computer and use it in GitHub Desktop.
Javacript sort array of object : http://stackoverflow.com/a/979325 demo : http://jsfiddle.net/dFNva/101/
<!-- To sort or not to sort, that is the question. -->
<h3>By price asc</h3>
<ul id="u1" style="margin-bottom: 20px;"></ul>
<h3>By city desc</h3>
<ul id="u2"></ul>
//from the second answer on this stackoverflow post
//http://stackoverflow.com/questions/979256/how-to-sort-an-array-of-javascript-objects
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"
}];
var sort_by = function(field, order, 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][+!!order];
}
}
// USAGE
// Sort by price low to high
homes.sort(sort_by('price', true, parseInt));
var u1 = document.getElementById('u1');
for (var i=0; i<homes.length; i++) {
u1.innerHTML += '<li>- '+homes[i].price+', '+homes[i].city+'</li>';
}
// Sort by city, case-insensitive, Z-A
homes.sort(sort_by('city', false, function(a){return a.toUpperCase()}));
var u2 = document.getElementById('u2');
for (i=0; i<homes.length; i++) {
u2.innerHTML += '<li>- '+homes[i].city+', '+homes[i].price+'</li>';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment