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

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

    I have seen a nice talk about making impossible state impossible. This covered the 2 arrays that are related but can go out of sync and better to use one array of objects that have 2 properties (as mentioned several times).

    However; if you want to mutate both arrays and sort them the same way you can do the following:

    //this will mutate both arrays passed into it
    //  you could return the arrays but then you need to do arr.slice(0).sort(...) instead
    const sortSame = sortFn => (arrayToSort,arrayToSortSame) => {
      const sortResults = [];
      arrayToSort.sort(//will mutate the array
        (a,b)=>{
          const result = sortFn(a,b);
          sortResults.push(result);
          return result
        }
      );
      arrayToSortSame.sort(()=>sortResults.shift());
      return undefined;
    }
    
    const priceArray= [1,5,3,7];
    const userIdArray=[11, 52, 41, 5];
    const numSortSameAscending = sortSame((a,b)=>a-b);
    numSortSameAscending(priceArray,userIdArray);
    console.log(
      priceArray,userIdArray
    )

    Even though the code in this answer may look simpler it is not the cheapest way to do it, as mapping is a cheaper operation than sorting (better to map 3 times and sort once then to sort twice) depending on the size of the arrays and how much the original array is out of order this way of sorting same may be very expensive.

提交回复
热议问题