Reputation: 60
I have an array of employee information that is sorted by comparison of the employee's sub department to the priority of sub-departments within a given department.
So when an employees name is clicked in an index, their department (stored as a data attribute) is used to grab all other employees sharing that department, and this collection is sorted by the subdepartment priority as-set manually in another array
var results = $.grep(data, function(employee) {
if(employee.DEPT == dept) {
return employee.DEPT = dept;
}
});
// ** NOTE 'deptorder' is "Department" : [ "Subdepartment1", "Subdepartment2" ] defined manually
// pick the order of subdepts based on the dept
order = deptorder[dept];
The first sort:
results.sort(function(a, b) {
return $.inArray(a.SUBDEPT, order) - $.inArray(b.SUBDEPT, order);
});
I then go through the sorted array and create a grid of employee info, with section headers dividing the employees by their sub department.
Problem: I need to arrange the employees within each sub department AFTER they have been sorted into sub department groups. I'm open to suggestions on how to do this, but all I need is to flag a 'manager' and make them first in the grid for their given sub department. After the manager is rendered the rest can fall to alphabetical, or whatever.
How can I sort the array a second time to achieve this? Right now managers have an employee.MANAGER attribute '1', while the rest have ''.
I've tried
results.sort(function(a, b) {
return (a.MANAGER == 1) - b;
});
but this doesn't work. The sorting shown above is my first and only experience with sort. Any help appreciated!
Upvotes: 0
Views: 114
Reputation: 413682
You can do all the comparisons in a single .sort()
pass:
results.sort(function(a, b) {
if (a.SUBDEPT == b.SUBDEPT) {
if (a.MANAGER == 1)
return -1; // a goes first
if (b.MANAGER == 1)
return 1; // b goes first
return 0; // or compare names
}
return $.inArray(a.SUBDEPT, order) - $.inArray(b.SUBDEPT, order);
}
In other words, while sorting, if you notice that you're comparing two elements in the same department, you check to see if either is the manager. If so, that one should go before the other one. If they're in different departments, then that's all that matters.
If they're in the same department but neither is a manager, you can then do the comparison by name or anything else you like.
Upvotes: 1