Sort array by order according to another array

后端 未结 6 1488
谎友^
谎友^ 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:17

    var objArray = [{id:1},{id:2},{id:3}];
    var sortOrder = [2,3,1];
    
    var newObjArray = [];
    for (i in sortOrder) {
        newObjArray.push(objArray[(sortOrder[i]) - 1])
    };
    

提交回复
热议问题