Wednesday, 8 May 2019

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)

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

No comments:

Post a Comment