Sort array by order according to another array

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

        function sortArrayByOrderArray(arr, orderArray) {
            return arr.sort(function(e1, e2) {
                return orderArray.indexOf(e1.id) - orderArray.indexOf(e2.id);
            });
        }
    
        console.log(sortArrayByOrderArray([{id:1},{id:2},{id:3}], [2,3,1]));

提交回复
热议问题