DEV Community

Clarice Bouwer
Clarice Bouwer

Posted on

How to create a string from values joining with commas and an and.

I have a vector of errors that looks like this:

(def messages 
  [{:error "Name is required"}
   {:error "Last name is required"}
   {:error "Date of birth is in the wrong format"}])
Enter fullscreen mode Exit fullscreen mode
(->> messages
  (map :error)
  (remove string/blank?)
  (string/join ", ")
  (#(string/replace % #", ([^,]+)$" " and $1")))
Enter fullscreen mode Exit fullscreen mode

The above form will output the following result:

"Name is required, Last name is required and Date of birth is in the wrong format"
Enter fullscreen mode Exit fullscreen mode

It uses a threaded macro to map through all :error keywords, removing blanks (and nils), joining by comma and then replacing the last comma with an and to read nicely.

This gives me a comma-separated list

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