Sort an array of objects based on another key array

advertisements

I have two arrays containing objects. One contains keys in some order and another has data and I need to sort the data array in order against the given sorted key array. How can I do this?

var a = ['d','a','b','c'] ;
var b =  [{a:1},{c:3},{d:4},{b:2}];

The result should be:

result = [{d:4},{a:1},{b:2},{c:3]


Try this

var a = ['d','a','b','c'] ;
var b =  [{a:1},{c:3},{d:4},{b:2}];

b.sort(function(x,y){
  var xkey = a.indexOf(Object.keys(x)[0]);
  var ykey = a.indexOf(Object.keys(y)[0]);
  return xkey - ykey;
})

document.body.innerHTML += JSON.stringify(b,0,4);