Javascript sort array of objects by array -


i have array of objects structured (this example) , array of id:

var array_objects=[         {id:'a',value:1},         {id:'b',value:2},         {id:'c',value:2},         {id:'d',value:3}         ];  var array =['b','c','a','d']; 

i wish reorder array_objects same way array ordered. order in array can change each time. how this?

a simple solution:

array_objects.sort(function(a,b){   return array.indexof(a.id)-array.indexof(b.id) }) 

if have big array , want fast, here's variant not calling indexof:

var m = array.reduce(function(r,k,i){ return r[k]=i,r },{}); array_objects.sort(function(a,b){ return m[a.id]-m[b.id] }); 

Comments

Popular posts from this blog

IF statement in MySQL trigger -

c++ - What does MSC in "// appease MSC" comments mean? -

javascript - Blogger related post gadget image Resize s72-c [ Need Expert Help ] -