I have 2 arrays
a = [2,3,1,4]
b = [{id: 1}, {id: 2}, {id: 3}, {id: 4}]
How do I get b sorted based on a? My desir
This solution uses Array#sort with a helper object c for the indices.
{
"1": 2,
"2": 0,
"3": 1,
"4": 3
}
var a = [2, 3, 1, 4],
b = [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }],
c = a.reduce(function (r, a, i) {
r[a] = i;
return r;
}, {});
b.sort(function (x, y) {
return c[x.id] - c[y.id];
});
document.write('' + JSON.stringify(b, 0, 4) + '
');
For greater objects, I suggest to use Sorting with map.