I have checked many questions and answers regarding join array with comma separated string, But my problem is that, I am making the string readable for human i.e I have tag
Another quick solution is to replace the last comma with and.
The following code:
var a = [0,1,2,3,4];
a.join(', ').replace(/,(?!.*,)/gmi, ' and');
should do the trick. (Also, play with the regex modifiers to your need).
One probable issue might be of time when you have large array, but it should work.
(note: you may skip to the end to find the final ready-to-pick code)
The one-liner from Blender's answer works great, though I'd favor something more understandable:
function arrayToText(a) {
if (a.length === 0) {
return '';
} else if (a.length === 1) {
return String(a[0]); // cast to string, for consistency with the other cases
} else if (a.length === 2) {
return a.join(' and ');
} else {
return a.slice(0, -1).join(', ') + ' and ' + a[a.length-1];
}
}
The same using a switch, see how nicer it is to read:
function arrayToText(a) {
switch (a.length) {
case 0:
return '';
case 1:
return String(a[0]); // cast to string, for consistency with the other cases
case 2:
return a.join(' and ');
default:
return a.slice(0, -1).join(', ') + ' and ' + a[a.length-1];
}
}
Of course, these codes can be shortened/optimized, for example by merging the "0", "1" and "2" cases into just the a.join(' and ')
from the case "2". I let you tweak these codes according to your taste :)
Finally, here is my end result, I think it has a great balance between understandability, shortness and efficiency:
function arrayToText(a) {
if (a.length <= 2) {
return a.join(' and ');
} else {
return a.slice(0, -1).join(', ') + ' and ' + a[a.length-1];
}
}
[1, 2, 3]
.join(', ')
.split('').reverse().join('')
.replace(' ,', ' dna ')
.split('').reverse().join('')
Able to solve it using reduce as well:
let items = [1, 2, 3, 4, 5];
items.reduce((acc, curr, i) =>
i !== 0 ? acc + `${items.length - 1 === i ? ` and ` : ', '}` + curr : curr, '');
// "1, 2, 3, 4 and 5"
Try this:
var substr = new Array("One", "Two", "Three");
var commaList = '';
var i;
for (i = 0; i < substr.length; ++i) {
if (i == substr.length - 1)
commaList += " and " + substr[i];
else
commaList += ", " + substr[i];
}
console.debug(commaList.substr(2, commaList.length));
You can use .slice()
:
> var a = [1, 2, 3, 4, 5];
> [a.slice(0, -1).join(', '), a.slice(-1)[0]].join(a.length < 2 ? '' : ' and ');
'1, 2, 3, 4 and 5'
a.slice(0, -1).join(', ')
: takes all but the last element and joins them together with a comma.a.slice(-1)[0]
: it's the last element..join(a.length < 2 ? '' : ' and ')
: joins that string and the last element with and
if there are at least two elements.