Javascript custom sort algorithm according to another array

后端 未结 4 1987
余生分开走
余生分开走 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:56

    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"]
    

提交回复
热议问题