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

后端 未结 4 1194
清酒与你
清酒与你 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:12

    Taken from Sorting with map and adapted for the userIdArray:

    // the array to be sorted
    var priceArray = [1, 5, 3, 7],
        userIdArray = [11, 52, 41, 5];
    
    // temporary array holds objects with position and sort-value
    var mapped = priceArray.map(function (el, i) {
        return { index: i, value: el };
    });
    
    // sorting the mapped array containing the reduced values
    mapped.sort(function (a, b) {
        return a.value - b.value;
    });
    
    // container for the resulting order
    var resultPrice = mapped.map(function (el) {
        return priceArray[el.index];
    });
    var resultUser = mapped.map(function (el) {
        return userIdArray[el.index];
    });
    
    document.write('
    ' + JSON.stringify(resultPrice, 0, 4) + '
    '); document.write('
    ' + JSON.stringify(resultUser, 0, 4) + '
    ');

    With proper data structure, as rrowland suggest, you might use this:

    var data = [{
            userId: 11, price: 1
        }, {
            userId: 52, price: 15
        }, {
            userId: 41, price: 13
        }, {
            userId: 5, price: 17
        }];
    
    data.sort(function (a, b) {
        return a.price - b.price;
    });
    
    document.write('
    ' + JSON.stringify(data, 0, 4) + '
    ');

    A bit shorter with ES6

    var priceArray = [1, 5, 3, 7],
        userIdArray = [11, 52, 41, 5],
        temp = Array.from(priceArray.keys()).sort((a, b) => priceArray[a] - priceArray[b]);
    
    priceArray = temp.map(i => priceArray[i]);
    userIdArray = temp.map(i => userIdArray[i]);
    
    console.log(priceArray);
    console.log(userIdArray);
    .as-console-wrapper { max-height: 100% !important; top: 0; }

提交回复
热议问题