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

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay