Sort array by order according to another array

后端 未结 6 1491
谎友^
谎友^ 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 14:55

    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))

提交回复
热议问题