javascript - 当条件相等时,javascript中的排序函数
问题描述
我想首先根据第二个单词对文件中的字符串进行排序,如果它们相等,则考虑第一个单词。在第 17 行,我如何添加条件来检查单词是否相同,然后根据第一个单词对其进行排序。
这是我的代码:https ://jsfiddle.net/am03uf7e/
var finalLine=[];
function testing() {
var logFileSize = 5;
var logLines = ["a1 9 2 3 1", "g1 act car", "z04 4 7", "ab1 off key dog", "a8 act zoo" ];
var newLinesw=[];
var newLinesn=[];
var wordsarray=[];
for(var i=0; i< logFileSize; i++) {
var words = logLines[i].split(" ");
if(isNaN(words[1]) )
newLinesw.push(logLines[i]);
else
newLinesn.push(logLines[i]);
}
newLinesw.sort(function(a,b){return a.split(" ")[1].localeCompare(b.split(" ")[1]); });
//To Do : apply condition for the same second word and sort by 1 word.
for(i=0;i<newLinesw.length;i++){
wordsarray.push(newLinesw[i].split(" ")[1]);
}
newLinesn.sort(function(a,b){return a.split(" ")[0].localeCompare(b.split(" ")[0]); });
finalLine = newLinesw.concat(newLinesn);
return finalLine;
}
document.getElementById("testing").innerHTML = testing();
解决方案
如果初始比较结果为 ,则用于||
测试第一个单词0
:
return a.split(" ")[1].localeCompare(b.split(" ")[1]) || a.split(" ")[0].localeCompare(b.split(" ")[0]);
但这很湿,很难阅读。最好为每个单词想出变量:
newLinesw.sort(function(a, b) {
const [a0, a1] = a.split(" ");
const [b0, b1] = b.split(" ");
return a1.localeCompare(b1) || a0.localeCompare(b0);
});
推荐阅读
- java - aws camunda zeebe ClientStatusException:超过 19.999991631 秒后的最后期限
- reactjs - 如果数据不是未定义的,你怎么能映射?
- javascript - 函数返回未捕获的引用错误
- node.js - 如何解决错误读取 ECONNRESET 公牛库
- bash - bash 中 printf 的默认 FORMAT 字符串是什么?
- ios - 支持 UITableView 的纵向和横向
- java - 类单例或组件。必须从不同的地方调用
- python - 两层菜单:我应该进行原始 SQL 查询吗?
- ruby-on-rails - Rails ActionMailer::Base.mail message-id 需要修复
- r - 过滤 tibble 中的 obs,其中变量包含来自另一个向量的任何子字符串