Is There A Way To Join The Elements In An Js Array, But Let The Last Separator Be Different?
What I want is something like Array.join(separator), but which takes a second argument Array.join(separator, beforeLastElement), so when I say [foo, bar, baz].join(', ', ' or') I w
Solution 1:
There's no predefined function, because it's quite simple.
var a = ['a', 'b', 'c'];
var str = a.slice(0, -1).join(',')+' or '+a.slice(-1);
There's also a specification problem for the main use case of such a function which is natural language formatting. For example if we were to use the Oxford comma logic we would have a different result than what you're looking for:
// make a list in the Oxford comma style (eg "a, b, c, and d")
// Examples with conjunction "and":
// ["a"] -> "a"
// ["a", "b"] -> "a and b"
// ["a", "b", "c"] -> "a, b, and c"
exports.oxford = function(arr, conjunction, ifempty){
let l = arr.length;
if (!l) return ifempty;
if (l<2) return arr[0];
if (l<3) return arr.join(` ${conjunction} `);
arr = arr.slice();
arr[l-1] = `${conjunction} ${arr[l-1]}`;
return arr.join(", ");
}
So it seems better to let this problem in userland.
Solution 2:
May I suggest:
['tom', 'dick', 'harry'].join(', ').replace(/, ([^,]*)$/, ' and $1')
> "tom, dick and harry"
Solution 3:
No, this is specific enough that you will have to write a custom function. The good news is, as you said, once you use Array.join
to take care of all the separators, the last one will be easy enough to update.
Solution 4:
In-line solution using reduce:
[1, 2, 3, 4, 5].reduce((text, value, i, array) => text + (i < array.length - 1 ? ', ' : ' or ') + value);
=> "1, 2, 3, 4 or 5"
Solution 5:
Building off of @dystroy's answer:
function formatArray(arr){
var outStr = "";
if (arr.length === 1) {
outStr = arr[0];
} else if (arr.length === 2) {
//joins all with "and" but no commas
//example: "bob and sam"
outStr = arr.join(' and ');
} else if (arr.length > 2) {
//joins all with commas, but last one gets ", and" (oxford comma!)
//example: "bob, joe, and sam"
outStr = arr.slice(0, -1).join(', ') + ', and ' + arr.slice(-1);
}
return outStr;
}
Example usages:
formatArray([]); //""
formatArray(["a"]); //"a"
formatArray(["a","b"]); //"a and b"
formatArray(["a","b","c"]); //"a, b, and c"
formatArray(["a","b","c","d"]); //"a, b, c, and d"
Post a Comment for "Is There A Way To Join The Elements In An Js Array, But Let The Last Separator Be Different?"