Imagine having a JSON object containing user colors that you want to sort by UserID.
oUserColors = { "users": [
{ "UserID": 31, "Color": "Red" },
{ "UserID": 30, "Color": "Red" },
{ "UserID": 32, "Color": "Green" },
{ "UserID": 30, "Color": "Green" },
{ "UserID": 32, "Color": "Red" }
] };
You can achieve this sorting using the following function.
objSortedUserColors = oUserColors.users.sort(function (a, b) {
return b.UserID - a.UserID; // sorting in descending order based on UserID.
});
The sorted result will look like this...
objSortedUserColors = { "users": [
{ "UserID": 32, "Color": "Red" },
{ "UserID": 32, "Color": "Green" },
{ "UserID": 31, "Color": "Red" },
{ "UserID": 30, "Color": "Red" },
{ "UserID": 30, "Color": "Green" }
] };
Now, what if you also want to filter out red colors for users who have both red and green? Leaving only green for those users with both colors.
objFilteredSortedUserColors = { "users": [
{ "UserID": 32, "Color": "Green" },
{ "UserID": 31, "Color": "Red" },
{ "UserID": 30, "Color": "Green" }
] };
If you have any ideas or suggestions on how to do this, please share!