This approach respects the keys in the objects of the array for sorting.
Only the items of a
are used for lookup and their respective order.
In this case d
gets all sort value of the item of b
, so d
looks like
[ 1, 3, 0, 2 ]
While sorting with indices, we need e
, which has simply the indices of b
[ 0, 1, 2, 3 ]
after sorting it became
[ 2, 0, 3, 1 ]
the wanted sort order. Now the original array is remapped to the new order.
But why?
Usually objects contains more than one property. If you use Object.keys
and take just the first element, then you could go wrong, because this element is not the wanted element for getting the sort order.
To make it save, you need a different approach, which does not use Array#indexOf
in combination with a fixed item of Object.keys
.
var a = ['d', 'a', 'b', 'c'],
b = [{ a: 1 }, { c: 3 }, { d: 4 }, { b: 2 }],
d = b.map(function (bb) {
var k = -1;
a.some(function (aa, i) {
if (aa in bb) {
k = i;
return true;
}
});
return k;
}),
e = b.map(function (_, i) { return i; });
e.sort(function (a, b) {
return d[a] - d[b];
});
b = e.map(function (a) {
return b[a];
});
document.write('<pre> ' + JSON.stringify(b, 0, 4) + '</pre>');