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.

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay