sort 2 array with the values of one of them in javascript

后端 未结 4 1196
清酒与你
清酒与你 2021-01-20 14:46

i have two array, lets say priceArray= [1,5,3,7]

userIdArray=[11, 52, 41, 5]

i need to sort the priceArray, so that the userIdArray will be also sorted. for

4条回答
  •  情话喂你
    2021-01-20 15:26

    Building on Rrowland's answer, you can create the array of objects with a library like lodash:

    var prices  = [1, 5, 8, 2];
    var userIds = [3, 5, 1, 9];
    
    var pairs = _.zipWith(prices, userIds, function(p, u) {
      return { price: p, userId: u };
    }); 
    

    This will give you an object like:

    [ 
      { price: 1, userId: 3 },
      { price: 5, userId: 5 },
      ... etc
    ]
    

    Then, for sorting, you can simply use a Javascript sort:

    pairs.sort(function(p) { return p.price });
    

    If you really need it as an array of userIds, you can get it back, after the sort:

    var sortedUserId = pairs.map( function(p) { return p.userId });
    // returns [ 3, 9, 5, 8 ];
    

提交回复
热议问题