I'm trying to sort an array of objects, but the property I'm sorting it by is not known beforehand. It's stored as a variable.
var items = [
{foo: "4", bar: "5"},
{foo: "7", bar: "1"},
{foo: "5", bar: "9"},
];
var whatToSort = "";
if (Math.random() > .5) {
whatToSort = "foo"
} else {
whatToSort = "bar"
};
items.sort(function(a, b){
return b.whatToSort - a.whatToSort;
};
This works if my sort()
function returns b.bar - a.bar
but not if the variable whatToSort
is used. Is there a way to do this?