I am currently working with a function that sorts by name and an array containing value/key pairs.
I am trying to figure out how I can dynamically pass the key on which the sort is being performed, so that I can call the same function each time with different keys:
var arr = [{name:'bob', artist:'rudy'},
{name:'johhny', artist:'drusko'},
{name:'tiff', artist:'needell'},
{name:'top', artist:'gear'}];
sort(arr, 'name'); //sort by name
sort(arr, 'artist'); //sort by artist
function sort(arr) {
arr.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)
});
}