There are many questions regarding sorting with JavaScript but I didn\'t find anything that addresses this case so I don\'t believe this is a duplicate.
I\'m getting dat
It's straightforward with lodash. The sortBy
function will move the items to the sortindex
position, so we just need to use find
to get the corresponding object, and return its sortindex
property for sortBy
to use.
var items = [{id:1, name:'bill'}, {id:2, name:'sam'}, {id:3, name: 'mary'}, {id:4, name:'jane'}];
var order = [{id:1, sortindex:4}, {id:2, sortindex:2}, {id:3, sortindex: 1}, {id:4, sortindex:3}];
var sorted = _.sortBy(items, function(item) {
// sorts by the value returned here
return _.find(order, function(ordItem) {
// find the object where the id's match
return item.id === ordItem.id;
}).sortindex; // that object's sortindex property is returned
});
document.body.textContent = JSON.stringify(sorted);