Javascript custom sort algorithm according to another array

后端 未结 4 1938
余生分开走
余生分开走 2021-01-25 18:55

I have this two arrays

var refArray = [\'India\',\'Pakistan\',\'Nepal\',\'Bhutan\',\'SreeLanka\',\'Singapore\',\'Thailand\',\'China\',\'Russia\']
var beenThere          


        
相关标签:
4条回答
  • 2021-01-25 19:41

    Try to use indexOf:

    beenThere.sort(function(a, b) {
        return refArray.indexOf(a) - refArray.indexOf(b); 
    }); // ['India','Bhutan','Russia']
    
    0 讨论(0)
  • 2021-01-25 19:47

    Just compare the indices of each element in the refArray using indexOf method.

    beenThere.sort(function(a,b){
    return refArray.indexOf(a)-refArray.indexOf(b);
    })
    
    0 讨论(0)
  • a faster way is to use the pre-sorted array as a template, and limit the indexOf() work to a single indexOf() call on the sub-set items, instead of 2-indexOf() calls on all items.

    var refArray = ['India','Pakistan','Nepal','Bhutan','SreeLanka','Singapore','Thailand','China','Russia']
    var beenThere = ['Russia','Bhutan','India'];
    function contains(a){return this.indexOf(a)!==-1; }
    refArray.filter(contains, beenThere); // == ["India", "Bhutan", "Russia"]
    
    0 讨论(0)
  • 2021-01-25 19:57

    since the data are strings, and the strings don't have commas, you can avoid all user-land iteration with a dynamic RegExp:

    var refArray = ['India','Pakistan','Nepal','Bhutan','SreeLanka','Singapore','Thailand','China','Russia']
    var beenThere = ['Russia','Bhutan','India'];
    
    
    (","+refArray+",").match(RegExp(",("+beenThere.join("|")+"),","g")).join(",").split(/,+/).slice(1,-1); 
    // ==  ["India", "Bhutan", "Russia"]
    

    that one is nice in that it doesn't need [].indexOf(), so it works in older browsers. you can use another delimeter besides comma if the data has commas, with some slightly uglier code...

    or, using filter for the iteration, but with a native method instead of a user-land function:

    var refArray = ['India','Pakistan','Nepal','Bhutan','SreeLanka','Singapore','Thailand','China','Russia']
    var beenThere = ['Russia','Bhutan','India'];
    
    refArray.filter(/./.test, RegExp("("+beenThere.join("|")+")","g"));
    // == ["India", "Bhutan", "Russia"]
    

    these would probably perform faster than indexOf(), but sorting is a weird operation, with lots of opportunity for behind-the-scenes optimization, so results may vary.

    0 讨论(0)
提交回复
热议问题