This question is close to this one: Sort array of objects by string property value in JavaScript
However, the field value should be chosen by the user (saved in the sortBy
parameter):
function sortList (sortBy, list) {
return list.sort(function (val1, val2) {
if (val1.sortBy > val2.sortBy) {
return -1;
}
if (val1.sortBy < val2.sortBy) {
return 1;
}
return 0;
});
}
var myObj = [
{a: 1, b: 3},
{a: 3, b: 2},
{a: 2, b: 40},
{a: 4, b: 12}
];
sortList(myObj.a, myObj);
The object returns unchanged.