Sorting array based on custom priority of one attribute
我使用jquery解析员工的JSON文件,其中包含他们的姓名、部门、子部门和其他一些详细信息。
例如。:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | [ { "LAST":"Betsy", "FIRST":"Jackson", "DEPT":"Customer Service", "SUBDEPT":"Tech Support", "JOINED":"02/94", "TITLE":"Technical Customer Service Representative", "RESIDENCE":"Someplace", "HOBBIES":"Reading, Walking, Sleeping" }, { "LAST":"Sally", "FIRST":"Smith", "DEPT":"Customer Service", "SUBDEPT":"Installation Customer Service Representative", "JOINED":"01/04", "TITLE":"Technical Customer Service Representative", "RESIDENCE":"Someplace", "HOBBIES":"Reading, Walking, Sleeping" }, ] |
我正在尝试构建一个应用程序,在该应用程序中,用户可以单击员工的姓名并查看结果的刷新,其中显示该员工部门中的每个员工,由子部门组织,并向下滚动到给定员工。
我已经成功地生成了一个员工姓名列表,其中包含数据-*属性以保存他们的部门和子部门。当一个雇员的名字被点击时,我第二次能够解析JSON文件,返回该部门的所有雇员,并构建一个网格,然后将整个匹配的雇员对象推到一个名为"results"的新数组中。
注意:dept=jquery选择器传递的数据部门。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | $.each(data, function(i, employee) { if (employee.DEPT == dept) { var employeetext = '<span class="name">' + employee.FIRST+' '+ employee.LAST+'</span>', employee.JOINED, employee.TITLE, employee.RESIDENCE, '...', employee.HOBBIES; $('#employees').append('<img src="" width="85" height="113">' + employeetext + '.'); results.push(employee); } }) // end stepping through employees |
号
但是,我需要根据数组中新的排序顺序构建网格,而不是按现在使用的字母顺序。我需要根据一个不是按字母顺序排列的优先级,而是一个我希望在单独对象中定义的自定义顺序,按子部门划分结果(这是一个"关系数据库吗?")例如:
1 2 3 4 5 6 7 8 9 10 | var subdeptorder = [ { "DEPT":"Marketing", "SUBDEPTS": ["Administration","Purchasing","Advertising","PR"] }, { "DEPT":"Sales", "SUBDEPTS": ["Administration","Business Development"] } ] |
因此,我需要根据员工所在部门(以及该部门的子部门顺序)对"结果"数组进行排序。
如何编写比较函数,根据在单独对象中建立的优先级对"结果"数组进行重新排序?
将单独的对象格式化如下:
1 2 3 4 | var subdeptorder = { "Marketing": ["Administration","Purchasing","Advertising","PR"], "Sales": ["Administration","Business Development"] }; |
然后您可以对数据进行如下排序:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | var dept = …; // the chosen one var results = $.grep(data, function(employee) { return employee.DEPT = dept; }), order = subdeptorder[dept]; results.sort(function(a, b) { // sort them by the indices of their SUBDEPTs in the order array return $.inArray(a.SUBDEPT, order) - $.inArray(b.SUBDEPT, order); }); $.each(results, function(i, employee) { $('#employees').append('<img src="" width="85" height="113">' + [ '<span class="name">'+employee.FIRST+' '+employee.LAST+'</span>', employee.JOINED, employee.TITLE, employee.RESIDENCE, '…', employee.HOBBIES ].join(' ') + '.'); }); |
号
有关优化版本,请参见按自定义顺序排序(每次索引都不使用