本文介绍了使用下划线排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用下划线 _.sortby()
函数对某些记录进行排序.我的要求是以 _ 开头的名称给予更高的优先级.例如.如果我的代码是
I am trying to sort certain records using underscore _.sortby()
function . My requirement is to give higher priority for names starting with _ . For eg . if my code is
var patients = [
[{name: 'John', roomNumber: 1, bedNumber: 1}],
[{name: 'Lisa', roomNumber: 1, bedNumber: 2}],
[{name: '_A', roomNumber: 2, bedNumber: 1}],
[{name: 'Omar', roomNumber: 3, bedNumber: 1}]
];
var sortedArray = _.sortBy(patients, function(patient) {
return patient[0].name;
});
我希望记录 _A, roomNumber: 2, bedNumber: 1 位于顶部.从某种意义上说,我希望排序忽略以 _
I would want to have the record _A, roomNumber: 2, bedNumber: 1 to be on the top . In a sense I want the sort to ignore the strings starting with _
推荐答案
试试这个代码.
var patients = [
[{name: '_John', roomNumber: 1, bedNumber: 1}],
[{name: 'Lisa', roomNumber: 1, bedNumber: 2}],
[{name: '_A', roomNumber: 2, bedNumber: 1}],
[{name: 'Amar', roomNumber: 3, bedNumber: 1}]
];
var sortedByChar = _.sortBy(patients, function(patient) {
return (patient[0].name.indexOf('_') != 0) ? patient[0].name[0] : patient[0].name[1];
});
var finalArray = _.sortBy(sortedByChar, function(patient) {
return (patient[0].name.indexOf('_') != 0);
});
alert(JSON.stringify(finalArray));
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
您可以通过在其他名称上添加下划线来玩弄小提琴,看看它是如何排序的.
You can play around with the fiddle by adding underscores to other names and see how it sorts.
这篇关于使用下划线排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!