Sort array by order according to another array

后端 未结 6 1480
谎友^
谎友^ 2021-02-09 14:49

I have an object that is being returned from a database like this: [{id:1},{id:2},{id:3}]. I have another array which specified the order the first array should be

6条回答
  •  无人及你
    2021-02-09 15:14

    To my understanding, sorting is not necessary; at least in your example, the desired resulting array can be generated in linear time as follows.

    var Result;
    for ( var i = 0; i < Input.length; i++ )
    {
        Result[i] = Input[Order[i]-1];
    }
    

    Here Result is the desired output, Input is your first array and Order the array containing the desired positions.

提交回复
热议问题