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
Mark Robinson
13.3k13 gold badges66 silver badges85 bronze badges
1 Answer 1
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
SLaks
891k182 gold badges1.9k silver badges2k bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
Mark Robinson
All in a single line! I'm impressed! Thanks for a great answer.
Tim Down
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 ")lang-js