Tuesday, October 6, 2020
Sort JSON Array with Value
Example:Sort JSON Array
mydata = [{ "id": 1, "first_name": "Jean", "last_name": "Esome", "age": 63}, { "id": 2, "first_name": "Rubi", "last_name": "Simonassi", "age": 18}, { "id": 3, "first_name": "Theo", "last_name": "Mully", "age": 34}, { "id": 4, "first_name": "Barbabra", "last_name": "Castagnasso", "age": 82}, { "id": 5, "first_name": "Mahmud", "last_name": "Boothebie", "age": 25}]; function sortResults(obj,prop, asc) { obj.sort(function(a, b) { if (asc) { return (a[prop] > b[prop]) ? 1 : ((a[prop] < b[prop]) ? -1 : 0); } else { return (b[prop] > a[prop]) ? 1 : ((b[prop] < a[prop]) ? -1 : 0); } }); } //Call Function sortResults(mydata,'first_name', false); // true = ascending / false = descending
Newer Posts
Older Posts
Home
View mobile version
Subscribe to:
Posts (Atom)