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
You can provide a custom comparison function to JavaScript's Array#sort method.
Use the custom comparison function to ensure the sort order:
var sortOrder = [2,3,1,4],
items = [{id: 1}, {id: 2}, {id: 3}, {id: 4}];
items.sort(function (a, b) {
return sortOrder.indexOf(a.id) - sortOrder.indexOf(b.id);
});
MDN:
- If compareFunction(a, b) returns less than 0, sort a to an index lower than b (i.e. a comes first).
- If compareFunction(a, b) returns 0, leave a and b unchanged with respect to each other, but sorted with respect to all different elements. Note: the ECMAscript standard does not guarantee this behavior, thus, not all browsers (e.g. Mozilla versions dating back to at least 2003) respect this.
- If compareFunction(a, b) returns greater than 0, sort b to an index lower than a (i.e. b comes first).