Having a list (array) of tags [\'tag1\', \'tag2\', \'tag3\']
I want to generate a nice title like: Content tagged tag1, tag2 and tag3
.
For the
A bit of slicing and dicing using Array.prototype.slice
:
function naturalLanguageJoin(arr){
if(!arr)
return '';
if(arr.length<2)
return (arr.length>0) ? arr[0] : '';
return arr.slice(0,arr.length-1).join(", ") + " and " + arr[arr.length-1];
}
console.log(naturalLanguageJoin(['tag1', 'tag2', 'tag3']));
console.log(naturalLanguageJoin(['tag1', 'tag2']));
console.log(naturalLanguageJoin(['tag1']));
console.log(naturalLanguageJoin([]));
console.log(naturalLanguageJoin(null));
Something like this would be my approach
function arrayFormat(arr) {
var output = arr.splice(0, arr.length - 1).join(", ");
output += " and " + arr[0];
return output;
}
console.log(arrayFormat(["a", "b", "c"]));
You could get the two last elements and join them with ' and '
and put it as last element back into the array and later join all elements with ', '
for getting a nice string.
Methods
Array#concat, joins two arrays and returns a new array
Array#splice, for getting the last two elemensts of the array
Array#join, joins an array with the given spacer.
This proposal works for any length of an array, even with one or two elements.
function nice([...array]) {
return array.concat(array.splice(-2, 2).join(' and ')).join(', ');
}
console.log("Content tagged " + nice(['tag1']));
console.log("Content tagged " + nice(['tag1', 'tag2']));
console.log("Content tagged " + nice(['tag1', 'tag2', 'tag3']));
Try this,
var arr = ['tag1', 'tag2', 'tag3'];
var lastStr = arr.pop();
var str = "Content tagged " + arr.join(", ") + " and " + lastStr;
From my view, This is an simple approach
var tags = ['tag1', 'tag2', 'tag3'];
console.log("Content tagged " + tags.slice(0, -1).join(', ')+' and '+tags.slice(-1));
Hope it helps you :) JsFiddle
An array can be treated as a stack so you can pop the last element and in turn write this
var last = tags_titles.pop();
last = tags_titles.length ? ` and ${last}` : last;
`Content tagged ${tags_titles.join(", ")} ${last}`
The code uses ES6 string templates, which I generally find to be more readable than doing string concatenation in the code. It also utilizes the fact that the pop method essentially performs to operations. Gets the lasst element of the array and mutate the array. That eliminate the need to do the mutation explicitly (using slice)