首页 > 解决方案 > 当条件相等时,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();

标签: javascript

解决方案


如果初始比较结果为 ,则用于||测试第一个单词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);
});

推荐阅读