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

Clarice Bouwer @cbillowes

About: Curious programmer sharing byte-sized knowledge on dev.to. Passionate about Git, GCP, TypeScript, Next.js, and DevTools. Enjoys collaborating with others and leading by example.

Location:
Mauritius
Joined:
May 30, 2018

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

Publish Date: Jul 3 '23
0 0

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

Comments 0 total

    Add comment