sort a dictionary (or whatever key-value data structure in js) on word_number keys efficiently

后端 未结 5 915
暗喜
暗喜 2020-12-11 14:54

how do I sort a dictionary by key like

dict[\"word_21\"] = \"Hello Java\";
dict[\"word_22\"] = \"Hello World\";
dict[\"word_11\"] = \"Hello Javascript\";
         


        
5条回答
  •  时光说笑
    2020-12-11 15:57

    @Amberlamps nice solution works most of the time. But, the OP is correct that there are splitting issues with certain keys. The default behavior of sort() in javascript is to use string Unicode code points to determine the order of the elements. For example, the following keys will not get sorted correctly using @Amberlamps method:

    canvas_2_1/15/2018__2:55:20_PM
    
    canvas_24_1/15/2018__2:55:20_PM
    

    But we can customize the sort method taking advantage of the fact that sort() accepts an optional argument which is a function that compares 2 elements of the array.

    By customizing the sort logic of the compare function and passing it to the sort() method the keys above get sorted correctly:

    sorted.sort(function(a, b) {
        a = parseInt(get_between(a, 'canvas_', '_'));
        b = parseInt(get_between(b, 'canvas_', '_'));
        if (a > b) {
            return 1;
        }
        if (b > a) {
            return -1;
        }
        return 0;
        });
    

    In this case I'm using the following get_between method:

    function get_between(str, char_a, char_b) {
       res = str.split(char_a).pop().split(char_b).shift();
       return(res)
    }
    

    Th point is, if you have tricky keys (which may or may not be "proper" use of dict) you can adapt the sort function to still sort correctly.

提交回复
热议问题