Yaakov Swissa Yaakov Swissa - 3 months ago 10
JSON Question

Sort JSON by other JSON with values

sort this json =

[{"id":"101", "name":"bla bla"},{"id":"102", "name":"bla bla"}]


by this json =

["102","101"]


result will be:
[{"id":"102", "name":"bla bla"},{"id":"101", "name":"bla bla"}]

Answer

There's the way that's okay for small arrays, which is to compare the indexOf each value of the key in the sort callback:

var target = [{"id":"101", "name":"bla bla"},{"id":"102", "name":"bla bla"}];

var order = ["102","101"];

target.sort(function(a, b) {
  return order.indexOf(a.id) - order.indexOf(b.id);
});

console.log(target);

Or the way that's more appropriate when the array with the order information is large, which is to build a map of indexes first:

var target = [{"id":"101", "name":"bla bla"},{"id":"102", "name":"bla bla"}];

var order = ["102","101"];

var map = Object.create(null);
order.forEach(function(value, index) {
  map[value] = index;
});

target.sort(function(a, b) {
  return map[a.id] - map[b.id];
});

console.log(target);

(Object.create(null) creates an object without a prototype, which I always do when I'm creating a mapping object to avoid inheriting any properties. In ES2015 and above you could use Map instead.)

Pick what suits your situation.