I made an array of objects and was able to sort by one of the properties of the objects (see bottom code). But I hardcoded which property to sort by (in this case "name"). How would I be able to pass to the sort method the property I am looking to sort by? I tried tmpArray.sort(function(a, b, sortBy) but got a no soup for you response. I know I can modify the array object with
array.prototype.thing = function(){ alert("hello world"); }
But is is possible for me to modify an existing method, like array.sort? Thanks.
$(document).ready(function(){
$(".sort").click(function() {
var tmpArray = new Array;
for (i=0; i<5; i++) {
var tmpObject = new Object;
switch(i) {
case 0 :
tmpObject.name = "Amy";
tmpObject.rank = 1;
tmpObject.priority = 3;
tmpObject.item = "Blue Item";
break;
case 1 :
tmpObject.name = "Jen";
tmpObject.rank = 2;
tmpObject.priority = 0;
tmpObject.item = "Red Item";
break;
case 2 :
tmpObject.name = "Mike";
tmpObject.rank = 3;
tmpObject.priority = 2;
tmpObject.item = "Green Item";
break;
case 3 :
tmpObject.name = "Raul";
tmpObject.rank = 4;
tmpObject.priority = 2;
tmpObject.item = "Yellow Item";
break;
case 4 :
tmpObject.name = "Lola";
tmpObject.rank = 5;
tmpObject.priority = 1;
tmpObject.item = "Blue Item";
break;
}
tmpArray.push(tmpObject);
}
tmpArray.sort(function(a, b) {
var nameA=a.name.toLowerCase(), nameB=b.name.toLowerCase()
if (nameA < nameB) //sort string ascending
return -1
if (nameA > nameB)
return 1
return 0 //default return value (no sorting)
});
console.log(tmpArray);
});
});