javascript, sort 2 array dependently

后端 未结 6 618
渐次进展
渐次进展 2021-01-04 10:09

for hours i\'ve been trying to figure out how to sort 2 array dependently.

Let\'s say I have 2 arrays.

First one:

array1 = [\'zzzzz\', \'aaaa         


        
6条回答
  •  执念已碎
    2021-01-04 10:44

    It just so happens I had some old code lying around that might do the trick:

    function arrVirtualSortGetIndices(array,fnCompare){
        var index=array.map(function(e,i,a){return i;});
        fnCompare=fnCompare || defaultStringCompare;
        var idxCompare=function (aa,bb){return fnCompare(array[aa],array[bb]);};
        index.sort(idxCompare);
        return index;
    
        function defaultStringCompare(aa,bb){
            if(aa

    Sorry, I don't do 'fors'. At least not when I don't have to.

    And fiddle.


    Also, an alternative fiddle that sorts the results when given an array of objects like this:

    given:

    var list = [
        {str:'zzzzz',value:3},
        {str:'aaaaa',value:7},
        {str:'ccccc',value:1}
    ];
    

    outputs:

    [
      {str: "aaaaa", value: 7},
      {str: "ccccc", value: 1},
      {str: "zzzzz", value: 3}
    ]
    

提交回复
热议问题