DEV Community

Dominic Myers
Dominic Myers

Posted on • Originally published at drmsite.blogspot.com on

lodash _.sortBy

I needed to order an array of objects in an arbitrary fashion, using strings which make sense to the business but aren't necessarily orderable otherwise. Unfortunately, I had to support IE11, so couldn't do fancy JS. Thankfully I had access to lodash. Anyway, I came up with this:

var statuses = ["one", "two", "three", "four"]; var complexObj = { dataset: [ { label: "two" },{ label: "four" },{ label: "three" },{ label: "one" }, ] }; console.table(complexObj.dataset); complexObj.dataset = _.sortBy(complexObj.dataset, function(n) { return _.indexOf(statuses, n.label); }); console.table(complexObj.dataset) 
Enter fullscreen mode Exit fullscreen mode

Which worked a treat, once I'd clocked I need to return the sorted array rather than merely sort it.

Top comments (0)