I have an array of JavaScript objects:
var people = [
{
"name": "Edward",
"age": 100,
"wallet": {
"location": "home",
"cash": 500
},
"bank": {
"location": "bank street",
"cash": 22100
}
},
{
"name": "Lisa",
"age": 30,
"wallet": {
"location": "home",
"cash": 20
},
"bank": {
"location": "bank street",
"cash": 12340
}
},
{
"name": "Elisabeth",
"age": 50,
"wallet": {
"location": "home",
"cash": 200
},
"bank": {
"location": "bank street",
"cash": 5000
}
}
];
How can I sort them by wallet.cash ?
This following example (by Ege Özcan) works if I wanted to sort these objects by name, or age, but I have hard time modifying it to work with multidimensional key.
function dynamicSort(property) {
var sortOrder = 1;
if(property[0] === "-") {
sortOrder = -1;
property = property.substr(1);
}
return function (a,b) {
var result = (a[property] < b[property]) ? -1 : (a[property] > b[property]) ? 1 : 0;
return result * sortOrder;
}
}
This works:
people.sort(dynamicSort("name"));
This doesn't:
people.sort(dynamicSort("wallet.cash"));
Thank you in advance!
You can pass two different arguments to dynamicSort function
And then call
DEMO