If I have an array in Javascript that looks like
searchComponents = ['element1', 'element2', 'element3'];
What is the necessary logic to turn it into a sentence like:
"element1, element2, and element3"
Likewise, if there are only two elements it should read like:
"element1 and element2"
and so on and so forth. I am stuck.
To convert an array to a comma-separated string, call the join() method on the array, passing it a string containing a comma as a parameter. The join method returns a string containing all array elements joined by the provided separator.
Join Together an Array as a String with Commas. When you need to join together every item in a JavaScript array to form a comma-separated list of values, use . join(",") or equivalently just . join() without any arguments at all.
One easy solution:
function arrayToSentence (arr) {
var last = arr.pop();
return arr.join(', ') + ' and ' + last;
}
console.log(arrayToSentence(['one','two','three']));
JS Fiddle demo.
And a slightly more complex/ridiculous solution (because who doesn't like silly, occasionally...):
function arrayToSentence (arr) {
var len = arr.length;
return arr.reduce(function(a,b,c){
return a + (c - 1 === length ? ', ' : ' and ') + b;
});
}
console.log(arrayToSentence(['one','two','three']));
JS Fiddle demo.
References:
Array.prototype.join()
.Array.prototype.pop()
.Array.prototype.reduce()
.function toSentence(arr) {
return arr.slice(0, -2).join(', ') +
(arr.slice(0, -2).length ? ', ' : '') +
arr.slice(-2).join(' and ');
}
usage
toSentence([1])
1
toSentence([1, 2])
1 and 2
toSentence([1, 2, 3])
1, 2 and 3
toSentence([1, 2, 3, 4, 5, 6])
1, 2, 3, 4, 5 and 6
Here's a one liner:
const arrayToSentence = (a) => [a.slice(0, -1).join(', '), a.pop()].filter(w => w !== '').join(' and ');
console.log(arrayToSentence(['foo', 'bar', 'baz']));
console.log(arrayToSentence(['foo', 'bar']));
console.log(arrayToSentence(['foo']));
console.log(arrayToSentence([]));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With