Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort object array based on another array of keys

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]
like image 579
A.T. Avatar asked Apr 14 '16 09:04

A.T.


People also ask

How do you sort an array of objects based on another array?

If you use the native array sort function, you can pass in a custom comparator to be used when sorting the array. The comparator should return a negative number if the first value is less than the second, zero if they're equal, and a positive number if the first value is greater.

How do I sort an array based on another Numpy?

Use the zip function: zip( *sorted( zip(arr1, arr2) ) ) This will do what you need.

How do you use indexOf in array of objects?

To find the index of an object in an array, by a specific property: Use the map() method to iterate over the array, returning only the value of the relevant property. Call the indexOf() method on the returned from map array. The indexOf method returns the index of the first occurrence of a value in an array.


1 Answers

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);
like image 183
gurvinder372 Avatar answered Sep 22 '22 20:09

gurvinder372