[英]Javascript custom sort with blanks
I am using the following code to sort a 2d array by column1 with a custom sort order, blanks naturally process as undefined and this is causing a problem when the array contains a series of blank rows.我正在使用以下代码按 column1 使用自定义排序顺序对二维数组进行排序,空白自然处理为未定义,当数组包含一系列空白行时,这会导致问题。 I would like undefined to basically behave as if it equaled 4 for the purpose of my sorting.
为了我的排序,我希望 undefined 基本上表现得好像它等于 4。 I'm wondering if I should implement some sort of switch statement to handle this situation but want to retain speed and code brevity.
我想知道我是否应该实现某种 switch 语句来处理这种情况,但希望保持速度和代码简洁。
var sortBy = {
"Order": 0,
"This": 1,
"Way": 2,
"Please": 3,
};
values.sort(function(a, b){
return sortBy[[a[0]][0]] - sortBy[[b[0]][0]];
});
The following modification greatly increases loading times, but maybe someone else can provide a more visually efficient solution.以下修改大大增加了加载时间,但也许其他人可以提供更直观的解决方案。
values.sort(function(a, b){
var current = typeof sortBy[[a[0]][0]] == 'undefined'?4:sortBy[[a[0]][0]];
var next = typeof sortBy[[b[0]][0]] == 'undefined'?4:sortBy[[b[0]][0]];
return current-next;
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.