如何以递归方式编写以下代码

时间:2019-08-05 08:57:07

标签: javascript

有一系列的二维数组需要按字母顺序排列。在已知的二维数组的情况下,我可以编写更多代码进行排序,但是没有显式的二维数组,我的代码功能有限:

let testArr=[[88, "Bowling Ball"], [2, "Dirty Sock"],  [3, "Hair Pin"],  [3, "Haaf-Eaten Apple"],  [5, "Microphone"],  [7, "Toothpaste"]]

function compare(arr1,arr2){

        if(arr1[1][0].charCodeAt()!==arr2[1][0].charCodeAt()){

            if(arr1[1][0].charCodeAt()<arr2[1][0].charCodeAt()){

                return -1;
            }else if(arr1[1][0].charCodeAt()>arr2[1][0].charCodeAt()){

                return 1;
            }else{
                return 0;
            }
        else if(arr1[1][0].charCodeAt()===arr2[1][0].charCodeAt()){
            if(arr1[1][1].charCodeAt()<arr2[1][1].charCodeAt()){
                return -1;
            }else if (arr1[1][1].charCodeAt()>arr2[1][1].charCodeAt()){
                return 1;
            }else{
                if(arr1[1][2].charCodeAt()<arr2[1][2].charCodeAt()){
                    return -1;
                }else if(arr1[1][2].charCodeAt()>arr2[1][2].charCodeAt()){
                    return 1;
                }else{
                    return 0;
    }

}

testArr.sort(compare)

期望有人提供递归解决方案

1 个答案:

答案 0 :(得分:1)

您可以通过获取数组的字符串来进行标准的除菌。

For a single classifier, the dataframe with results look like this : 

label   predictedAns    predictedProb
1       2                 0.999281
2       2                 0.999754
2       2                 0.999754
3       3                 0.999762
2       2                 0.999641
2       2                 0.999641
2       2                 0.9996

一种递归方法,先获取第一个字符并检查顺序,然后获取其余部分以再次调用该函数。

var array = [[88, "Bowling Ball"], [2, "Dirty Sock"], [3, "Hair Pin"], [3, "Haaf-Eaten Apple"], [5, "Microphone"], [7, "Toothpaste"]];

array.sort(([, a], [, b]) => a.localeCompare(b));

console.log(array);

相关问题