Reputation: 13329
Say I have a this:
["Done", "Pending", "Busy"]
How would I sort that so the order is busy, pending, done?
I will have a list of objects, each with a status value of either done, pending and busy. So there might be 100's.
Im not sure how this works, because its not alphabetical or logical, its based on user preference.
I want them to always be i that order.
Im using javascript to sort the array.
Checksum: "e791e37b19187712fc95078e8fd2b367"
FileLastWriteTimeUtc: "2013/06/07 01:22:40 PM"
FileName: "1.jpg"
PartsSuccess: 0
PartsTotal: 0
Path: "\Image Content Tests"
Size: 4174754
Status: "Done"
Thanks
Upvotes: 1
Views: 443
Reputation: 25091
Assuming your list of objects is an array, use a custom sort function:
sortMe.sort(function (a, b) {
var statusA = ['Busy', 'Pending', 'Done'].indexOf(a.Status),
statusB = ['Busy', 'Pending', 'Done'].indexOf(b.Status);
return statusA - statusB;
});
where sortMe
is something like the following:
var sortMe = [{
"Checksum": "e791e37b19187712fc95078e8fd2b367",
"FileLastWriteTimeUtc": "2013/06/07 01:22:40 PM",
"FileName": "1.jpg",
"PartsSuccess": 0,
"PartsTotal": 0,
"Path": "\Image Content Tests",
"Size": 4174754,
"Status": "Done"
},{
"Checksum": "e791e37b19187712fc95078e8fd2b367",
"FileLastWriteTimeUtc": "2013/06/07 01:22:40 PM",
"FileName": "2.jpg",
"PartsSuccess": 0,
"PartsTotal": 0,
"Path": "\Image Content Tests",
"Size": 4174754,
"Status": "Busy"
},{
"Checksum": "e791e37b19187712fc95078e8fd2b367",
"FileLastWriteTimeUtc": "2013/06/07 01:22:40 PM",
"FileName": "3.jpg",
"PartsSuccess": 0,
"PartsTotal": 0,
"Path": "\Image Content Tests",
"Size": 4174754,
"Status": "Pending"
}];
Upvotes: 0
Reputation: 92875
I assume that you have objects like
[
{
'name' : 'Sending mail to manager',
'status': 'pending'
},
{
'name' : 'Talking to girl friend',
'status': 'busy'
},
{
'name' : 'Breakfast',
'status': 'done'
},
]
I suggest you to use underscorejs
_.sortBy(a, function(obj) {
if (obj.status === 'busy') {
return 1;
} else if (obj.status === 'pending') {
return 2;
}
return 3;
})
Upvotes: -1
Reputation: 1356
You assign each of your values a sort order. This sort order is a number, and entirely up to you on what to make them. You then sort by the sort order of the value you actually want to sort. An example:
var data = [
{
id: 1,
state: "Pending"
},
{
id: 2,
state: "Done"
},
{
id: 3,
state: "Busy"
}
];
var sortOrders = {
"Done": 1,
"Busy": 2,
"Pending": 3
};
data.sort(function(a, b) {
return sortOrders[a.state] - sortOrders[b.state];
});
demo: http://ideone.com/qsz52d
Upvotes: 5