6

If you have an array of strings in JavaScript / JQuery:

var myStrings = ["item1", "item2", "item3", "item4"];

...what is the most elegant way you have found to convert that list to a readable english phrase of the form:

"item1, item2, item3 and item4"

The function must also work with:

var myStrings = ["item1"]; // produces "item1"
var myStrings = ["item1", "item2"]; // produces "item1 and item2"
asked Jan 24, 2011 at 14:12

1 Answer 1

14

Like this:

a.length == 1 ? a[0] : [ a.slice(0, a.length - 1).join(", "), a[a.length - 1] ].join(" and ")
answered Jan 24, 2011 at 14:16
Sign up to request clarification or add additional context in comments.

2 Comments

All in a single line! I'm impressed! Thanks for a great answer.
You can shorten it slightly by using slice's support for negative indices: a.length == 1 ? a[0] : [ a.slice(0, -1).join(", "), a[a.length - 1] ].join(" and ")

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.