Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort array by order according to another array

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 sorted in, like this: [2,3,1].

I'm looking for a method or algorithm that can take in these two arrays and return [{id:2},{id:3},{id:1}]. Ideally it should be sort of efficient and not n squared.

like image 953
Alexis Avatar asked Dec 04 '14 09:12

Alexis


2 Answers

If you want linear time, first build a hashtable from the first array and then pick items in order by looping the second one:

data = [{id:5},{id:2},{id:9}]
order = [9,5,2]

hash = {}
data.forEach(function(x) { hash[x.id] = x })

sorted = order.map(function(x) { return hash[x] })

document.write(JSON.stringify(sorted))
like image 142
georg Avatar answered Nov 10 '22 04:11

georg


    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]));
like image 3
Barmar Avatar answered Nov 10 '22 04:11

Barmar