Join an array by commas and “and”
I want to convert the array ['one', 'two', 'three', 'four']
into one, two, three and four
Note that the first items have a comma, and but there is the word and
between the second-last one and the last one.
The best solution I've come up with:
a.reduce( (res, v, i) => i === a.length - 2 ? res + v + ' and ' : res + v + ( i == a.length -1? '' : ', '), '' )
It's based on adding the commas at the end -- with the exception of the second-last one (a.length - 2
) and with a way to avoid the last comma (a.length - 2
).
SURELY there must be a better, neater, more intelligent way to do this?
It's a difficult topic to search on search engines because it contains the word "and"...
javascript arrays string
|
show 3 more comments
I want to convert the array ['one', 'two', 'three', 'four']
into one, two, three and four
Note that the first items have a comma, and but there is the word and
between the second-last one and the last one.
The best solution I've come up with:
a.reduce( (res, v, i) => i === a.length - 2 ? res + v + ' and ' : res + v + ( i == a.length -1? '' : ', '), '' )
It's based on adding the commas at the end -- with the exception of the second-last one (a.length - 2
) and with a way to avoid the last comma (a.length - 2
).
SURELY there must be a better, neater, more intelligent way to do this?
It's a difficult topic to search on search engines because it contains the word "and"...
javascript arrays string
14
SURELY you value the serial/Oxford comma?!?
– Argalatyr
Dec 21 '18 at 5:35
You mean I should returnone, two, three, and four
?
– Merc
Dec 21 '18 at 5:48
@Merc: Indeed, that's how it looks with the Oxford comma. Currently, there are two schools: some people prefer the Oxford comma, while others prefer not to use it. Although I personally always use the Oxford comma, IIRC, Oxford itself has stopped advocating it.
– Andreas Rejbrand
Dec 21 '18 at 12:19
There is something very Oxford about now referring to "The So Recently Oxford Comma".
– jdv
Dec 21 '18 at 15:46
@AndreasRejbrand reference on disuse by Oxford Press? I haven't seen that, and it makes little sense to me. The serial comma seems always clearer, and the challenge of specifying the alternative (e.g. question above) illustrates the consistency of the serial comma.
– Argalatyr
Dec 23 '18 at 12:35
|
show 3 more comments
I want to convert the array ['one', 'two', 'three', 'four']
into one, two, three and four
Note that the first items have a comma, and but there is the word and
between the second-last one and the last one.
The best solution I've come up with:
a.reduce( (res, v, i) => i === a.length - 2 ? res + v + ' and ' : res + v + ( i == a.length -1? '' : ', '), '' )
It's based on adding the commas at the end -- with the exception of the second-last one (a.length - 2
) and with a way to avoid the last comma (a.length - 2
).
SURELY there must be a better, neater, more intelligent way to do this?
It's a difficult topic to search on search engines because it contains the word "and"...
javascript arrays string
I want to convert the array ['one', 'two', 'three', 'four']
into one, two, three and four
Note that the first items have a comma, and but there is the word and
between the second-last one and the last one.
The best solution I've come up with:
a.reduce( (res, v, i) => i === a.length - 2 ? res + v + ' and ' : res + v + ( i == a.length -1? '' : ', '), '' )
It's based on adding the commas at the end -- with the exception of the second-last one (a.length - 2
) and with a way to avoid the last comma (a.length - 2
).
SURELY there must be a better, neater, more intelligent way to do this?
It's a difficult topic to search on search engines because it contains the word "and"...
javascript arrays string
javascript arrays string
edited Dec 21 '18 at 6:48
Bergi
366k58546872
366k58546872
asked Dec 21 '18 at 4:15
MercMerc
6,91294788
6,91294788
14
SURELY you value the serial/Oxford comma?!?
– Argalatyr
Dec 21 '18 at 5:35
You mean I should returnone, two, three, and four
?
– Merc
Dec 21 '18 at 5:48
@Merc: Indeed, that's how it looks with the Oxford comma. Currently, there are two schools: some people prefer the Oxford comma, while others prefer not to use it. Although I personally always use the Oxford comma, IIRC, Oxford itself has stopped advocating it.
– Andreas Rejbrand
Dec 21 '18 at 12:19
There is something very Oxford about now referring to "The So Recently Oxford Comma".
– jdv
Dec 21 '18 at 15:46
@AndreasRejbrand reference on disuse by Oxford Press? I haven't seen that, and it makes little sense to me. The serial comma seems always clearer, and the challenge of specifying the alternative (e.g. question above) illustrates the consistency of the serial comma.
– Argalatyr
Dec 23 '18 at 12:35
|
show 3 more comments
14
SURELY you value the serial/Oxford comma?!?
– Argalatyr
Dec 21 '18 at 5:35
You mean I should returnone, two, three, and four
?
– Merc
Dec 21 '18 at 5:48
@Merc: Indeed, that's how it looks with the Oxford comma. Currently, there are two schools: some people prefer the Oxford comma, while others prefer not to use it. Although I personally always use the Oxford comma, IIRC, Oxford itself has stopped advocating it.
– Andreas Rejbrand
Dec 21 '18 at 12:19
There is something very Oxford about now referring to "The So Recently Oxford Comma".
– jdv
Dec 21 '18 at 15:46
@AndreasRejbrand reference on disuse by Oxford Press? I haven't seen that, and it makes little sense to me. The serial comma seems always clearer, and the challenge of specifying the alternative (e.g. question above) illustrates the consistency of the serial comma.
– Argalatyr
Dec 23 '18 at 12:35
14
14
SURELY you value the serial/Oxford comma?!?
– Argalatyr
Dec 21 '18 at 5:35
SURELY you value the serial/Oxford comma?!?
– Argalatyr
Dec 21 '18 at 5:35
You mean I should return
one, two, three, and four
?– Merc
Dec 21 '18 at 5:48
You mean I should return
one, two, three, and four
?– Merc
Dec 21 '18 at 5:48
@Merc: Indeed, that's how it looks with the Oxford comma. Currently, there are two schools: some people prefer the Oxford comma, while others prefer not to use it. Although I personally always use the Oxford comma, IIRC, Oxford itself has stopped advocating it.
– Andreas Rejbrand
Dec 21 '18 at 12:19
@Merc: Indeed, that's how it looks with the Oxford comma. Currently, there are two schools: some people prefer the Oxford comma, while others prefer not to use it. Although I personally always use the Oxford comma, IIRC, Oxford itself has stopped advocating it.
– Andreas Rejbrand
Dec 21 '18 at 12:19
There is something very Oxford about now referring to "The So Recently Oxford Comma".
– jdv
Dec 21 '18 at 15:46
There is something very Oxford about now referring to "The So Recently Oxford Comma".
– jdv
Dec 21 '18 at 15:46
@AndreasRejbrand reference on disuse by Oxford Press? I haven't seen that, and it makes little sense to me. The serial comma seems always clearer, and the challenge of specifying the alternative (e.g. question above) illustrates the consistency of the serial comma.
– Argalatyr
Dec 23 '18 at 12:35
@AndreasRejbrand reference on disuse by Oxford Press? I haven't seen that, and it makes little sense to me. The serial comma seems always clearer, and the challenge of specifying the alternative (e.g. question above) illustrates the consistency of the serial comma.
– Argalatyr
Dec 23 '18 at 12:35
|
show 3 more comments
6 Answers
6
active
oldest
votes
One option would be to pop
the last item, then join
all the rest by commas, and concatenate with and
plus the last item:
const input = ['one', 'two', 'three', 'four'];
const last = input.pop();
const result = input.join(', ') + ' and ' + last;
console.log(result);
If you can't mutate the input array, use slice
instead, and if there might only be one item in the input array, check the length of the array first:
function makeString(arr) {
if (arr.length === 1) return arr[0];
const firsts = arr.slice(0, arr.length - 1);
const last = arr[arr.length - 1];
return firsts.join(', ') + ' and ' + last;
}
console.log(makeString(['one', 'two', 'three', 'four']));
console.log(makeString(['one']));
Might have to be some guards on lengths, and it's the same-same approach I'd probably recommend.
– user2864740
Dec 21 '18 at 4:22
1
I love this, and it's just so simple -- especially simple to read (I am a great fan of code maintenance)
– Merc
Dec 21 '18 at 4:25
I think this is hard to beat, but I am waiting a little before accepting in case it attracts even better answers. But, I love it
– Merc
Dec 21 '18 at 4:26
6
Very nice, thought the lack of the Oxford comma is killing me.
– Mark Meyer
Dec 21 '18 at 4:43
As an echo to an other answer, you may want to pushlast
back ininput
(you know, "modifying the inputs when it's not the output is bad" and stuff like that...)
– Kaiido
Dec 21 '18 at 4:53
add a comment |
I like Mark Meyer's approach (and would upvote if I had the rep) as it doesn't alter the input. Here's my spin:
function makeCommaSeparatedString(arr, useOxfordComma) {
const listStart = arr.slice(0, -1).join(', ');
const listEnd = arr.slice(-1);
const conjunction = arr.length <= 1 ? '' :
useOxfordComma && arr.length > 2 ? ', and ' : ' and ';
return [listStart, listEnd].join(conjunction);
}
console.log(makeCommaSeparatedString(['one', 'two', 'three', 'four']));
// one, two, three and four
console.log(makeCommaSeparatedString(['one', 'two', 'three', 'four'], true));
// one, two, three, and four
console.log(makeCommaSeparatedString(['one', 'two'], true));
// one and two
console.log(makeCommaSeparatedString(['one']));
// one
console.log(makeCommaSeparatedString());
//
add a comment |
Starting in V8 v7.2 and Chrome 72, you can use the sweet Intl.ListFormat
API. It will also take care of localizing your list when requested, which might be of great help if you need it.
const lf = new Intl.ListFormat('en');
lf.format(['Frank']);
// → 'Frank'
lf.format(['Frank', 'Christine']);
// → 'Frank and Christine'
lf.format(['Frank', 'Christine', 'Flora']);
// → 'Frank, Christine, and Flora'
lf.format(['Frank', 'Christine', 'Flora', 'Harrison']);
// → 'Frank, Christine, Flora, and Harrison'
You can even specify options to make it a disruption and use "or" instead of "and", or to format units such as "3 ft, 7 in".
References
The Intl.ListFormat API - Google Developers
V8 release v7.2
add a comment |
You can use Array.prototype.slice() when array.length
is bigger than 1 and exclude the rest of the cases:
a.length > 1 ? `${a.slice(0, -1).join(', ')} and ${a.slice(-1)}` : {0: '', 1: a[0]}[a.length]
Code example:
const input1 = ['one', 'two', 'three', 'four'];
const input2 = ['A Tale of Two Cities', 'Harry Potter and the smth', 'One Fish, Two Fish, Red Fish, Blue Fish'];
const input3 = ['one', 'two'];
const input4 = ['one'];
const input5 = ;
const result = a => a.length > 1
? `${a.slice(0, -1).join(', ')} and ${a.slice(-1)}`
: {0: '', 1: a[0]}[a.length];
console.log(result(input1));
console.log(result(input2));
console.log(result(input3));
console.log(result(input4));
console.log(result(input5));
1
Easy to introduce subtle issues that'll be found later (outside of a restricted set of input):['A Tale of Two Cities', 'Harry Potter and the smth', 'One Fish, Two Fish, Red Fish, Blue Fish']
– user2864740
Dec 21 '18 at 4:23
@user2864740 Good comment, thanks
– Yosvel Quintero
Dec 21 '18 at 4:24
1
@user2864740 I have updated my answer for that type ofinput
data..
– Yosvel Quintero
Dec 21 '18 at 4:39
1
I like this solution a lot. However, if input only has ONE value = 'VALUE', it returns 'and VALUE'
– Merc
Dec 21 '18 at 5:55
You are right @Merc, I have added validation..
– Yosvel Quintero
Dec 21 '18 at 6:37
add a comment |
Another approach could be using the splice method to remove the last two elements of the array and join they using the and
token. After this, you could push this result again on the array, and finally join all elements using the ,
separator.
Updated to:
1) Show how this works for multiple cases (no extra control needed over the array length).
2) Wrap the logic inside a method.
3) Do not mutate the original array (if not required).
let arrayToCustomStr = (arr, enableMutate) =>
{
// Clone the received array (if required).
let a = enableMutate ? arr : arr.slice(0);
// Convert the array to custom string.
let removed = a.splice(-2, 2);
a.push(removed.join(" and "));
return a.join(", ");
}
// First example, mutate of original array is disabled.
let input1 = ['one', 'two', 'three', 'four'];
console.log("Result for input1:" , arrayToCustomStr(input1));
console.log("Original input1:", input1);
// Second example, mutate of original array is enabled.
let input2 = ['one', 'two'];
console.log("Result for input2:", arrayToCustomStr(input2, true));
console.log("Original input2:", input2);
// Third example, lenght of array is 1.
let input3 = ['one'];
console.log("Result for input3:", arrayToCustomStr(input3));
// Fourth example, empty array.
let input4 = ;
console.log("Result for input4:", arrayToCustomStr(input4));
// Plus example.
let bob = [
"Don't worry about a thing",
"Cause every little thing",
"Gonna be all right",
"Saying, don't worry about a thing..."
];
console.log("Result for bob:", arrayToCustomStr(bob));
.as-console-wrapper {
top: 0px;
max-height: 100% !important;
}
add a comment |
Using Array#reduce:
['one', 'two', 'three', 'four'].reduce(
(a, b, i, array) => a + (i < array.length - 1 ? ', ' : ' and ') + b)
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53879088%2fjoin-an-array-by-commas-and-and%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
6 Answers
6
active
oldest
votes
6 Answers
6
active
oldest
votes
active
oldest
votes
active
oldest
votes
One option would be to pop
the last item, then join
all the rest by commas, and concatenate with and
plus the last item:
const input = ['one', 'two', 'three', 'four'];
const last = input.pop();
const result = input.join(', ') + ' and ' + last;
console.log(result);
If you can't mutate the input array, use slice
instead, and if there might only be one item in the input array, check the length of the array first:
function makeString(arr) {
if (arr.length === 1) return arr[0];
const firsts = arr.slice(0, arr.length - 1);
const last = arr[arr.length - 1];
return firsts.join(', ') + ' and ' + last;
}
console.log(makeString(['one', 'two', 'three', 'four']));
console.log(makeString(['one']));
Might have to be some guards on lengths, and it's the same-same approach I'd probably recommend.
– user2864740
Dec 21 '18 at 4:22
1
I love this, and it's just so simple -- especially simple to read (I am a great fan of code maintenance)
– Merc
Dec 21 '18 at 4:25
I think this is hard to beat, but I am waiting a little before accepting in case it attracts even better answers. But, I love it
– Merc
Dec 21 '18 at 4:26
6
Very nice, thought the lack of the Oxford comma is killing me.
– Mark Meyer
Dec 21 '18 at 4:43
As an echo to an other answer, you may want to pushlast
back ininput
(you know, "modifying the inputs when it's not the output is bad" and stuff like that...)
– Kaiido
Dec 21 '18 at 4:53
add a comment |
One option would be to pop
the last item, then join
all the rest by commas, and concatenate with and
plus the last item:
const input = ['one', 'two', 'three', 'four'];
const last = input.pop();
const result = input.join(', ') + ' and ' + last;
console.log(result);
If you can't mutate the input array, use slice
instead, and if there might only be one item in the input array, check the length of the array first:
function makeString(arr) {
if (arr.length === 1) return arr[0];
const firsts = arr.slice(0, arr.length - 1);
const last = arr[arr.length - 1];
return firsts.join(', ') + ' and ' + last;
}
console.log(makeString(['one', 'two', 'three', 'four']));
console.log(makeString(['one']));
Might have to be some guards on lengths, and it's the same-same approach I'd probably recommend.
– user2864740
Dec 21 '18 at 4:22
1
I love this, and it's just so simple -- especially simple to read (I am a great fan of code maintenance)
– Merc
Dec 21 '18 at 4:25
I think this is hard to beat, but I am waiting a little before accepting in case it attracts even better answers. But, I love it
– Merc
Dec 21 '18 at 4:26
6
Very nice, thought the lack of the Oxford comma is killing me.
– Mark Meyer
Dec 21 '18 at 4:43
As an echo to an other answer, you may want to pushlast
back ininput
(you know, "modifying the inputs when it's not the output is bad" and stuff like that...)
– Kaiido
Dec 21 '18 at 4:53
add a comment |
One option would be to pop
the last item, then join
all the rest by commas, and concatenate with and
plus the last item:
const input = ['one', 'two', 'three', 'four'];
const last = input.pop();
const result = input.join(', ') + ' and ' + last;
console.log(result);
If you can't mutate the input array, use slice
instead, and if there might only be one item in the input array, check the length of the array first:
function makeString(arr) {
if (arr.length === 1) return arr[0];
const firsts = arr.slice(0, arr.length - 1);
const last = arr[arr.length - 1];
return firsts.join(', ') + ' and ' + last;
}
console.log(makeString(['one', 'two', 'three', 'four']));
console.log(makeString(['one']));
One option would be to pop
the last item, then join
all the rest by commas, and concatenate with and
plus the last item:
const input = ['one', 'two', 'three', 'four'];
const last = input.pop();
const result = input.join(', ') + ' and ' + last;
console.log(result);
If you can't mutate the input array, use slice
instead, and if there might only be one item in the input array, check the length of the array first:
function makeString(arr) {
if (arr.length === 1) return arr[0];
const firsts = arr.slice(0, arr.length - 1);
const last = arr[arr.length - 1];
return firsts.join(', ') + ' and ' + last;
}
console.log(makeString(['one', 'two', 'three', 'four']));
console.log(makeString(['one']));
const input = ['one', 'two', 'three', 'four'];
const last = input.pop();
const result = input.join(', ') + ' and ' + last;
console.log(result);
const input = ['one', 'two', 'three', 'four'];
const last = input.pop();
const result = input.join(', ') + ' and ' + last;
console.log(result);
function makeString(arr) {
if (arr.length === 1) return arr[0];
const firsts = arr.slice(0, arr.length - 1);
const last = arr[arr.length - 1];
return firsts.join(', ') + ' and ' + last;
}
console.log(makeString(['one', 'two', 'three', 'four']));
console.log(makeString(['one']));
function makeString(arr) {
if (arr.length === 1) return arr[0];
const firsts = arr.slice(0, arr.length - 1);
const last = arr[arr.length - 1];
return firsts.join(', ') + ' and ' + last;
}
console.log(makeString(['one', 'two', 'three', 'four']));
console.log(makeString(['one']));
edited Dec 21 '18 at 6:04
answered Dec 21 '18 at 4:17
CertainPerformanceCertainPerformance
80.3k143865
80.3k143865
Might have to be some guards on lengths, and it's the same-same approach I'd probably recommend.
– user2864740
Dec 21 '18 at 4:22
1
I love this, and it's just so simple -- especially simple to read (I am a great fan of code maintenance)
– Merc
Dec 21 '18 at 4:25
I think this is hard to beat, but I am waiting a little before accepting in case it attracts even better answers. But, I love it
– Merc
Dec 21 '18 at 4:26
6
Very nice, thought the lack of the Oxford comma is killing me.
– Mark Meyer
Dec 21 '18 at 4:43
As an echo to an other answer, you may want to pushlast
back ininput
(you know, "modifying the inputs when it's not the output is bad" and stuff like that...)
– Kaiido
Dec 21 '18 at 4:53
add a comment |
Might have to be some guards on lengths, and it's the same-same approach I'd probably recommend.
– user2864740
Dec 21 '18 at 4:22
1
I love this, and it's just so simple -- especially simple to read (I am a great fan of code maintenance)
– Merc
Dec 21 '18 at 4:25
I think this is hard to beat, but I am waiting a little before accepting in case it attracts even better answers. But, I love it
– Merc
Dec 21 '18 at 4:26
6
Very nice, thought the lack of the Oxford comma is killing me.
– Mark Meyer
Dec 21 '18 at 4:43
As an echo to an other answer, you may want to pushlast
back ininput
(you know, "modifying the inputs when it's not the output is bad" and stuff like that...)
– Kaiido
Dec 21 '18 at 4:53
Might have to be some guards on lengths, and it's the same-same approach I'd probably recommend.
– user2864740
Dec 21 '18 at 4:22
Might have to be some guards on lengths, and it's the same-same approach I'd probably recommend.
– user2864740
Dec 21 '18 at 4:22
1
1
I love this, and it's just so simple -- especially simple to read (I am a great fan of code maintenance)
– Merc
Dec 21 '18 at 4:25
I love this, and it's just so simple -- especially simple to read (I am a great fan of code maintenance)
– Merc
Dec 21 '18 at 4:25
I think this is hard to beat, but I am waiting a little before accepting in case it attracts even better answers. But, I love it
– Merc
Dec 21 '18 at 4:26
I think this is hard to beat, but I am waiting a little before accepting in case it attracts even better answers. But, I love it
– Merc
Dec 21 '18 at 4:26
6
6
Very nice, thought the lack of the Oxford comma is killing me.
– Mark Meyer
Dec 21 '18 at 4:43
Very nice, thought the lack of the Oxford comma is killing me.
– Mark Meyer
Dec 21 '18 at 4:43
As an echo to an other answer, you may want to push
last
back in input
(you know, "modifying the inputs when it's not the output is bad" and stuff like that...)– Kaiido
Dec 21 '18 at 4:53
As an echo to an other answer, you may want to push
last
back in input
(you know, "modifying the inputs when it's not the output is bad" and stuff like that...)– Kaiido
Dec 21 '18 at 4:53
add a comment |
I like Mark Meyer's approach (and would upvote if I had the rep) as it doesn't alter the input. Here's my spin:
function makeCommaSeparatedString(arr, useOxfordComma) {
const listStart = arr.slice(0, -1).join(', ');
const listEnd = arr.slice(-1);
const conjunction = arr.length <= 1 ? '' :
useOxfordComma && arr.length > 2 ? ', and ' : ' and ';
return [listStart, listEnd].join(conjunction);
}
console.log(makeCommaSeparatedString(['one', 'two', 'three', 'four']));
// one, two, three and four
console.log(makeCommaSeparatedString(['one', 'two', 'three', 'four'], true));
// one, two, three, and four
console.log(makeCommaSeparatedString(['one', 'two'], true));
// one and two
console.log(makeCommaSeparatedString(['one']));
// one
console.log(makeCommaSeparatedString());
//
add a comment |
I like Mark Meyer's approach (and would upvote if I had the rep) as it doesn't alter the input. Here's my spin:
function makeCommaSeparatedString(arr, useOxfordComma) {
const listStart = arr.slice(0, -1).join(', ');
const listEnd = arr.slice(-1);
const conjunction = arr.length <= 1 ? '' :
useOxfordComma && arr.length > 2 ? ', and ' : ' and ';
return [listStart, listEnd].join(conjunction);
}
console.log(makeCommaSeparatedString(['one', 'two', 'three', 'four']));
// one, two, three and four
console.log(makeCommaSeparatedString(['one', 'two', 'three', 'four'], true));
// one, two, three, and four
console.log(makeCommaSeparatedString(['one', 'two'], true));
// one and two
console.log(makeCommaSeparatedString(['one']));
// one
console.log(makeCommaSeparatedString());
//
add a comment |
I like Mark Meyer's approach (and would upvote if I had the rep) as it doesn't alter the input. Here's my spin:
function makeCommaSeparatedString(arr, useOxfordComma) {
const listStart = arr.slice(0, -1).join(', ');
const listEnd = arr.slice(-1);
const conjunction = arr.length <= 1 ? '' :
useOxfordComma && arr.length > 2 ? ', and ' : ' and ';
return [listStart, listEnd].join(conjunction);
}
console.log(makeCommaSeparatedString(['one', 'two', 'three', 'four']));
// one, two, three and four
console.log(makeCommaSeparatedString(['one', 'two', 'three', 'four'], true));
// one, two, three, and four
console.log(makeCommaSeparatedString(['one', 'two'], true));
// one and two
console.log(makeCommaSeparatedString(['one']));
// one
console.log(makeCommaSeparatedString());
//
I like Mark Meyer's approach (and would upvote if I had the rep) as it doesn't alter the input. Here's my spin:
function makeCommaSeparatedString(arr, useOxfordComma) {
const listStart = arr.slice(0, -1).join(', ');
const listEnd = arr.slice(-1);
const conjunction = arr.length <= 1 ? '' :
useOxfordComma && arr.length > 2 ? ', and ' : ' and ';
return [listStart, listEnd].join(conjunction);
}
console.log(makeCommaSeparatedString(['one', 'two', 'three', 'four']));
// one, two, three and four
console.log(makeCommaSeparatedString(['one', 'two', 'three', 'four'], true));
// one, two, three, and four
console.log(makeCommaSeparatedString(['one', 'two'], true));
// one and two
console.log(makeCommaSeparatedString(['one']));
// one
console.log(makeCommaSeparatedString());
//
function makeCommaSeparatedString(arr, useOxfordComma) {
const listStart = arr.slice(0, -1).join(', ');
const listEnd = arr.slice(-1);
const conjunction = arr.length <= 1 ? '' :
useOxfordComma && arr.length > 2 ? ', and ' : ' and ';
return [listStart, listEnd].join(conjunction);
}
console.log(makeCommaSeparatedString(['one', 'two', 'three', 'four']));
// one, two, three and four
console.log(makeCommaSeparatedString(['one', 'two', 'three', 'four'], true));
// one, two, three, and four
console.log(makeCommaSeparatedString(['one', 'two'], true));
// one and two
console.log(makeCommaSeparatedString(['one']));
// one
console.log(makeCommaSeparatedString());
//
function makeCommaSeparatedString(arr, useOxfordComma) {
const listStart = arr.slice(0, -1).join(', ');
const listEnd = arr.slice(-1);
const conjunction = arr.length <= 1 ? '' :
useOxfordComma && arr.length > 2 ? ', and ' : ' and ';
return [listStart, listEnd].join(conjunction);
}
console.log(makeCommaSeparatedString(['one', 'two', 'three', 'four']));
// one, two, three and four
console.log(makeCommaSeparatedString(['one', 'two', 'three', 'four'], true));
// one, two, three, and four
console.log(makeCommaSeparatedString(['one', 'two'], true));
// one and two
console.log(makeCommaSeparatedString(['one']));
// one
console.log(makeCommaSeparatedString());
//
answered Dec 21 '18 at 5:18
JugJug
1362
1362
add a comment |
add a comment |
Starting in V8 v7.2 and Chrome 72, you can use the sweet Intl.ListFormat
API. It will also take care of localizing your list when requested, which might be of great help if you need it.
const lf = new Intl.ListFormat('en');
lf.format(['Frank']);
// → 'Frank'
lf.format(['Frank', 'Christine']);
// → 'Frank and Christine'
lf.format(['Frank', 'Christine', 'Flora']);
// → 'Frank, Christine, and Flora'
lf.format(['Frank', 'Christine', 'Flora', 'Harrison']);
// → 'Frank, Christine, Flora, and Harrison'
You can even specify options to make it a disruption and use "or" instead of "and", or to format units such as "3 ft, 7 in".
References
The Intl.ListFormat API - Google Developers
V8 release v7.2
add a comment |
Starting in V8 v7.2 and Chrome 72, you can use the sweet Intl.ListFormat
API. It will also take care of localizing your list when requested, which might be of great help if you need it.
const lf = new Intl.ListFormat('en');
lf.format(['Frank']);
// → 'Frank'
lf.format(['Frank', 'Christine']);
// → 'Frank and Christine'
lf.format(['Frank', 'Christine', 'Flora']);
// → 'Frank, Christine, and Flora'
lf.format(['Frank', 'Christine', 'Flora', 'Harrison']);
// → 'Frank, Christine, Flora, and Harrison'
You can even specify options to make it a disruption and use "or" instead of "and", or to format units such as "3 ft, 7 in".
References
The Intl.ListFormat API - Google Developers
V8 release v7.2
add a comment |
Starting in V8 v7.2 and Chrome 72, you can use the sweet Intl.ListFormat
API. It will also take care of localizing your list when requested, which might be of great help if you need it.
const lf = new Intl.ListFormat('en');
lf.format(['Frank']);
// → 'Frank'
lf.format(['Frank', 'Christine']);
// → 'Frank and Christine'
lf.format(['Frank', 'Christine', 'Flora']);
// → 'Frank, Christine, and Flora'
lf.format(['Frank', 'Christine', 'Flora', 'Harrison']);
// → 'Frank, Christine, Flora, and Harrison'
You can even specify options to make it a disruption and use "or" instead of "and", or to format units such as "3 ft, 7 in".
References
The Intl.ListFormat API - Google Developers
V8 release v7.2
Starting in V8 v7.2 and Chrome 72, you can use the sweet Intl.ListFormat
API. It will also take care of localizing your list when requested, which might be of great help if you need it.
const lf = new Intl.ListFormat('en');
lf.format(['Frank']);
// → 'Frank'
lf.format(['Frank', 'Christine']);
// → 'Frank and Christine'
lf.format(['Frank', 'Christine', 'Flora']);
// → 'Frank, Christine, and Flora'
lf.format(['Frank', 'Christine', 'Flora', 'Harrison']);
// → 'Frank, Christine, Flora, and Harrison'
You can even specify options to make it a disruption and use "or" instead of "and", or to format units such as "3 ft, 7 in".
References
The Intl.ListFormat API - Google Developers
V8 release v7.2
const lf = new Intl.ListFormat('en');
lf.format(['Frank']);
// → 'Frank'
lf.format(['Frank', 'Christine']);
// → 'Frank and Christine'
lf.format(['Frank', 'Christine', 'Flora']);
// → 'Frank, Christine, and Flora'
lf.format(['Frank', 'Christine', 'Flora', 'Harrison']);
// → 'Frank, Christine, Flora, and Harrison'
const lf = new Intl.ListFormat('en');
lf.format(['Frank']);
// → 'Frank'
lf.format(['Frank', 'Christine']);
// → 'Frank and Christine'
lf.format(['Frank', 'Christine', 'Flora']);
// → 'Frank, Christine, and Flora'
lf.format(['Frank', 'Christine', 'Flora', 'Harrison']);
// → 'Frank, Christine, Flora, and Harrison'
answered Dec 21 '18 at 11:08
Baptiste CandellierBaptiste Candellier
29629
29629
add a comment |
add a comment |
You can use Array.prototype.slice() when array.length
is bigger than 1 and exclude the rest of the cases:
a.length > 1 ? `${a.slice(0, -1).join(', ')} and ${a.slice(-1)}` : {0: '', 1: a[0]}[a.length]
Code example:
const input1 = ['one', 'two', 'three', 'four'];
const input2 = ['A Tale of Two Cities', 'Harry Potter and the smth', 'One Fish, Two Fish, Red Fish, Blue Fish'];
const input3 = ['one', 'two'];
const input4 = ['one'];
const input5 = ;
const result = a => a.length > 1
? `${a.slice(0, -1).join(', ')} and ${a.slice(-1)}`
: {0: '', 1: a[0]}[a.length];
console.log(result(input1));
console.log(result(input2));
console.log(result(input3));
console.log(result(input4));
console.log(result(input5));
1
Easy to introduce subtle issues that'll be found later (outside of a restricted set of input):['A Tale of Two Cities', 'Harry Potter and the smth', 'One Fish, Two Fish, Red Fish, Blue Fish']
– user2864740
Dec 21 '18 at 4:23
@user2864740 Good comment, thanks
– Yosvel Quintero
Dec 21 '18 at 4:24
1
@user2864740 I have updated my answer for that type ofinput
data..
– Yosvel Quintero
Dec 21 '18 at 4:39
1
I like this solution a lot. However, if input only has ONE value = 'VALUE', it returns 'and VALUE'
– Merc
Dec 21 '18 at 5:55
You are right @Merc, I have added validation..
– Yosvel Quintero
Dec 21 '18 at 6:37
add a comment |
You can use Array.prototype.slice() when array.length
is bigger than 1 and exclude the rest of the cases:
a.length > 1 ? `${a.slice(0, -1).join(', ')} and ${a.slice(-1)}` : {0: '', 1: a[0]}[a.length]
Code example:
const input1 = ['one', 'two', 'three', 'four'];
const input2 = ['A Tale of Two Cities', 'Harry Potter and the smth', 'One Fish, Two Fish, Red Fish, Blue Fish'];
const input3 = ['one', 'two'];
const input4 = ['one'];
const input5 = ;
const result = a => a.length > 1
? `${a.slice(0, -1).join(', ')} and ${a.slice(-1)}`
: {0: '', 1: a[0]}[a.length];
console.log(result(input1));
console.log(result(input2));
console.log(result(input3));
console.log(result(input4));
console.log(result(input5));
1
Easy to introduce subtle issues that'll be found later (outside of a restricted set of input):['A Tale of Two Cities', 'Harry Potter and the smth', 'One Fish, Two Fish, Red Fish, Blue Fish']
– user2864740
Dec 21 '18 at 4:23
@user2864740 Good comment, thanks
– Yosvel Quintero
Dec 21 '18 at 4:24
1
@user2864740 I have updated my answer for that type ofinput
data..
– Yosvel Quintero
Dec 21 '18 at 4:39
1
I like this solution a lot. However, if input only has ONE value = 'VALUE', it returns 'and VALUE'
– Merc
Dec 21 '18 at 5:55
You are right @Merc, I have added validation..
– Yosvel Quintero
Dec 21 '18 at 6:37
add a comment |
You can use Array.prototype.slice() when array.length
is bigger than 1 and exclude the rest of the cases:
a.length > 1 ? `${a.slice(0, -1).join(', ')} and ${a.slice(-1)}` : {0: '', 1: a[0]}[a.length]
Code example:
const input1 = ['one', 'two', 'three', 'four'];
const input2 = ['A Tale of Two Cities', 'Harry Potter and the smth', 'One Fish, Two Fish, Red Fish, Blue Fish'];
const input3 = ['one', 'two'];
const input4 = ['one'];
const input5 = ;
const result = a => a.length > 1
? `${a.slice(0, -1).join(', ')} and ${a.slice(-1)}`
: {0: '', 1: a[0]}[a.length];
console.log(result(input1));
console.log(result(input2));
console.log(result(input3));
console.log(result(input4));
console.log(result(input5));
You can use Array.prototype.slice() when array.length
is bigger than 1 and exclude the rest of the cases:
a.length > 1 ? `${a.slice(0, -1).join(', ')} and ${a.slice(-1)}` : {0: '', 1: a[0]}[a.length]
Code example:
const input1 = ['one', 'two', 'three', 'four'];
const input2 = ['A Tale of Two Cities', 'Harry Potter and the smth', 'One Fish, Two Fish, Red Fish, Blue Fish'];
const input3 = ['one', 'two'];
const input4 = ['one'];
const input5 = ;
const result = a => a.length > 1
? `${a.slice(0, -1).join(', ')} and ${a.slice(-1)}`
: {0: '', 1: a[0]}[a.length];
console.log(result(input1));
console.log(result(input2));
console.log(result(input3));
console.log(result(input4));
console.log(result(input5));
const input1 = ['one', 'two', 'three', 'four'];
const input2 = ['A Tale of Two Cities', 'Harry Potter and the smth', 'One Fish, Two Fish, Red Fish, Blue Fish'];
const input3 = ['one', 'two'];
const input4 = ['one'];
const input5 = ;
const result = a => a.length > 1
? `${a.slice(0, -1).join(', ')} and ${a.slice(-1)}`
: {0: '', 1: a[0]}[a.length];
console.log(result(input1));
console.log(result(input2));
console.log(result(input3));
console.log(result(input4));
console.log(result(input5));
const input1 = ['one', 'two', 'three', 'four'];
const input2 = ['A Tale of Two Cities', 'Harry Potter and the smth', 'One Fish, Two Fish, Red Fish, Blue Fish'];
const input3 = ['one', 'two'];
const input4 = ['one'];
const input5 = ;
const result = a => a.length > 1
? `${a.slice(0, -1).join(', ')} and ${a.slice(-1)}`
: {0: '', 1: a[0]}[a.length];
console.log(result(input1));
console.log(result(input2));
console.log(result(input3));
console.log(result(input4));
console.log(result(input5));
edited Dec 23 '18 at 2:07
answered Dec 21 '18 at 4:21
Yosvel QuinteroYosvel Quintero
11k42329
11k42329
1
Easy to introduce subtle issues that'll be found later (outside of a restricted set of input):['A Tale of Two Cities', 'Harry Potter and the smth', 'One Fish, Two Fish, Red Fish, Blue Fish']
– user2864740
Dec 21 '18 at 4:23
@user2864740 Good comment, thanks
– Yosvel Quintero
Dec 21 '18 at 4:24
1
@user2864740 I have updated my answer for that type ofinput
data..
– Yosvel Quintero
Dec 21 '18 at 4:39
1
I like this solution a lot. However, if input only has ONE value = 'VALUE', it returns 'and VALUE'
– Merc
Dec 21 '18 at 5:55
You are right @Merc, I have added validation..
– Yosvel Quintero
Dec 21 '18 at 6:37
add a comment |
1
Easy to introduce subtle issues that'll be found later (outside of a restricted set of input):['A Tale of Two Cities', 'Harry Potter and the smth', 'One Fish, Two Fish, Red Fish, Blue Fish']
– user2864740
Dec 21 '18 at 4:23
@user2864740 Good comment, thanks
– Yosvel Quintero
Dec 21 '18 at 4:24
1
@user2864740 I have updated my answer for that type ofinput
data..
– Yosvel Quintero
Dec 21 '18 at 4:39
1
I like this solution a lot. However, if input only has ONE value = 'VALUE', it returns 'and VALUE'
– Merc
Dec 21 '18 at 5:55
You are right @Merc, I have added validation..
– Yosvel Quintero
Dec 21 '18 at 6:37
1
1
Easy to introduce subtle issues that'll be found later (outside of a restricted set of input):
['A Tale of Two Cities', 'Harry Potter and the smth', 'One Fish, Two Fish, Red Fish, Blue Fish']
– user2864740
Dec 21 '18 at 4:23
Easy to introduce subtle issues that'll be found later (outside of a restricted set of input):
['A Tale of Two Cities', 'Harry Potter and the smth', 'One Fish, Two Fish, Red Fish, Blue Fish']
– user2864740
Dec 21 '18 at 4:23
@user2864740 Good comment, thanks
– Yosvel Quintero
Dec 21 '18 at 4:24
@user2864740 Good comment, thanks
– Yosvel Quintero
Dec 21 '18 at 4:24
1
1
@user2864740 I have updated my answer for that type of
input
data..– Yosvel Quintero
Dec 21 '18 at 4:39
@user2864740 I have updated my answer for that type of
input
data..– Yosvel Quintero
Dec 21 '18 at 4:39
1
1
I like this solution a lot. However, if input only has ONE value = 'VALUE', it returns 'and VALUE'
– Merc
Dec 21 '18 at 5:55
I like this solution a lot. However, if input only has ONE value = 'VALUE', it returns 'and VALUE'
– Merc
Dec 21 '18 at 5:55
You are right @Merc, I have added validation..
– Yosvel Quintero
Dec 21 '18 at 6:37
You are right @Merc, I have added validation..
– Yosvel Quintero
Dec 21 '18 at 6:37
add a comment |
Another approach could be using the splice method to remove the last two elements of the array and join they using the and
token. After this, you could push this result again on the array, and finally join all elements using the ,
separator.
Updated to:
1) Show how this works for multiple cases (no extra control needed over the array length).
2) Wrap the logic inside a method.
3) Do not mutate the original array (if not required).
let arrayToCustomStr = (arr, enableMutate) =>
{
// Clone the received array (if required).
let a = enableMutate ? arr : arr.slice(0);
// Convert the array to custom string.
let removed = a.splice(-2, 2);
a.push(removed.join(" and "));
return a.join(", ");
}
// First example, mutate of original array is disabled.
let input1 = ['one', 'two', 'three', 'four'];
console.log("Result for input1:" , arrayToCustomStr(input1));
console.log("Original input1:", input1);
// Second example, mutate of original array is enabled.
let input2 = ['one', 'two'];
console.log("Result for input2:", arrayToCustomStr(input2, true));
console.log("Original input2:", input2);
// Third example, lenght of array is 1.
let input3 = ['one'];
console.log("Result for input3:", arrayToCustomStr(input3));
// Fourth example, empty array.
let input4 = ;
console.log("Result for input4:", arrayToCustomStr(input4));
// Plus example.
let bob = [
"Don't worry about a thing",
"Cause every little thing",
"Gonna be all right",
"Saying, don't worry about a thing..."
];
console.log("Result for bob:", arrayToCustomStr(bob));
.as-console-wrapper {
top: 0px;
max-height: 100% !important;
}
add a comment |
Another approach could be using the splice method to remove the last two elements of the array and join they using the and
token. After this, you could push this result again on the array, and finally join all elements using the ,
separator.
Updated to:
1) Show how this works for multiple cases (no extra control needed over the array length).
2) Wrap the logic inside a method.
3) Do not mutate the original array (if not required).
let arrayToCustomStr = (arr, enableMutate) =>
{
// Clone the received array (if required).
let a = enableMutate ? arr : arr.slice(0);
// Convert the array to custom string.
let removed = a.splice(-2, 2);
a.push(removed.join(" and "));
return a.join(", ");
}
// First example, mutate of original array is disabled.
let input1 = ['one', 'two', 'three', 'four'];
console.log("Result for input1:" , arrayToCustomStr(input1));
console.log("Original input1:", input1);
// Second example, mutate of original array is enabled.
let input2 = ['one', 'two'];
console.log("Result for input2:", arrayToCustomStr(input2, true));
console.log("Original input2:", input2);
// Third example, lenght of array is 1.
let input3 = ['one'];
console.log("Result for input3:", arrayToCustomStr(input3));
// Fourth example, empty array.
let input4 = ;
console.log("Result for input4:", arrayToCustomStr(input4));
// Plus example.
let bob = [
"Don't worry about a thing",
"Cause every little thing",
"Gonna be all right",
"Saying, don't worry about a thing..."
];
console.log("Result for bob:", arrayToCustomStr(bob));
.as-console-wrapper {
top: 0px;
max-height: 100% !important;
}
add a comment |
Another approach could be using the splice method to remove the last two elements of the array and join they using the and
token. After this, you could push this result again on the array, and finally join all elements using the ,
separator.
Updated to:
1) Show how this works for multiple cases (no extra control needed over the array length).
2) Wrap the logic inside a method.
3) Do not mutate the original array (if not required).
let arrayToCustomStr = (arr, enableMutate) =>
{
// Clone the received array (if required).
let a = enableMutate ? arr : arr.slice(0);
// Convert the array to custom string.
let removed = a.splice(-2, 2);
a.push(removed.join(" and "));
return a.join(", ");
}
// First example, mutate of original array is disabled.
let input1 = ['one', 'two', 'three', 'four'];
console.log("Result for input1:" , arrayToCustomStr(input1));
console.log("Original input1:", input1);
// Second example, mutate of original array is enabled.
let input2 = ['one', 'two'];
console.log("Result for input2:", arrayToCustomStr(input2, true));
console.log("Original input2:", input2);
// Third example, lenght of array is 1.
let input3 = ['one'];
console.log("Result for input3:", arrayToCustomStr(input3));
// Fourth example, empty array.
let input4 = ;
console.log("Result for input4:", arrayToCustomStr(input4));
// Plus example.
let bob = [
"Don't worry about a thing",
"Cause every little thing",
"Gonna be all right",
"Saying, don't worry about a thing..."
];
console.log("Result for bob:", arrayToCustomStr(bob));
.as-console-wrapper {
top: 0px;
max-height: 100% !important;
}
Another approach could be using the splice method to remove the last two elements of the array and join they using the and
token. After this, you could push this result again on the array, and finally join all elements using the ,
separator.
Updated to:
1) Show how this works for multiple cases (no extra control needed over the array length).
2) Wrap the logic inside a method.
3) Do not mutate the original array (if not required).
let arrayToCustomStr = (arr, enableMutate) =>
{
// Clone the received array (if required).
let a = enableMutate ? arr : arr.slice(0);
// Convert the array to custom string.
let removed = a.splice(-2, 2);
a.push(removed.join(" and "));
return a.join(", ");
}
// First example, mutate of original array is disabled.
let input1 = ['one', 'two', 'three', 'four'];
console.log("Result for input1:" , arrayToCustomStr(input1));
console.log("Original input1:", input1);
// Second example, mutate of original array is enabled.
let input2 = ['one', 'two'];
console.log("Result for input2:", arrayToCustomStr(input2, true));
console.log("Original input2:", input2);
// Third example, lenght of array is 1.
let input3 = ['one'];
console.log("Result for input3:", arrayToCustomStr(input3));
// Fourth example, empty array.
let input4 = ;
console.log("Result for input4:", arrayToCustomStr(input4));
// Plus example.
let bob = [
"Don't worry about a thing",
"Cause every little thing",
"Gonna be all right",
"Saying, don't worry about a thing..."
];
console.log("Result for bob:", arrayToCustomStr(bob));
.as-console-wrapper {
top: 0px;
max-height: 100% !important;
}
let arrayToCustomStr = (arr, enableMutate) =>
{
// Clone the received array (if required).
let a = enableMutate ? arr : arr.slice(0);
// Convert the array to custom string.
let removed = a.splice(-2, 2);
a.push(removed.join(" and "));
return a.join(", ");
}
// First example, mutate of original array is disabled.
let input1 = ['one', 'two', 'three', 'four'];
console.log("Result for input1:" , arrayToCustomStr(input1));
console.log("Original input1:", input1);
// Second example, mutate of original array is enabled.
let input2 = ['one', 'two'];
console.log("Result for input2:", arrayToCustomStr(input2, true));
console.log("Original input2:", input2);
// Third example, lenght of array is 1.
let input3 = ['one'];
console.log("Result for input3:", arrayToCustomStr(input3));
// Fourth example, empty array.
let input4 = ;
console.log("Result for input4:", arrayToCustomStr(input4));
// Plus example.
let bob = [
"Don't worry about a thing",
"Cause every little thing",
"Gonna be all right",
"Saying, don't worry about a thing..."
];
console.log("Result for bob:", arrayToCustomStr(bob));
.as-console-wrapper {
top: 0px;
max-height: 100% !important;
}
let arrayToCustomStr = (arr, enableMutate) =>
{
// Clone the received array (if required).
let a = enableMutate ? arr : arr.slice(0);
// Convert the array to custom string.
let removed = a.splice(-2, 2);
a.push(removed.join(" and "));
return a.join(", ");
}
// First example, mutate of original array is disabled.
let input1 = ['one', 'two', 'three', 'four'];
console.log("Result for input1:" , arrayToCustomStr(input1));
console.log("Original input1:", input1);
// Second example, mutate of original array is enabled.
let input2 = ['one', 'two'];
console.log("Result for input2:", arrayToCustomStr(input2, true));
console.log("Original input2:", input2);
// Third example, lenght of array is 1.
let input3 = ['one'];
console.log("Result for input3:", arrayToCustomStr(input3));
// Fourth example, empty array.
let input4 = ;
console.log("Result for input4:", arrayToCustomStr(input4));
// Plus example.
let bob = [
"Don't worry about a thing",
"Cause every little thing",
"Gonna be all right",
"Saying, don't worry about a thing..."
];
console.log("Result for bob:", arrayToCustomStr(bob));
.as-console-wrapper {
top: 0px;
max-height: 100% !important;
}
edited Dec 23 '18 at 15:21
answered Dec 21 '18 at 4:49
ShiderszShidersz
4,8042629
4,8042629
add a comment |
add a comment |
Using Array#reduce:
['one', 'two', 'three', 'four'].reduce(
(a, b, i, array) => a + (i < array.length - 1 ? ', ' : ' and ') + b)
add a comment |
Using Array#reduce:
['one', 'two', 'three', 'four'].reduce(
(a, b, i, array) => a + (i < array.length - 1 ? ', ' : ' and ') + b)
add a comment |
Using Array#reduce:
['one', 'two', 'three', 'four'].reduce(
(a, b, i, array) => a + (i < array.length - 1 ? ', ' : ' and ') + b)
Using Array#reduce:
['one', 'two', 'three', 'four'].reduce(
(a, b, i, array) => a + (i < array.length - 1 ? ', ' : ' and ') + b)
answered Dec 21 '18 at 16:27
xqc winston mainxqc winston main
111
111
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53879088%2fjoin-an-array-by-commas-and-and%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
14
SURELY you value the serial/Oxford comma?!?
– Argalatyr
Dec 21 '18 at 5:35
You mean I should return
one, two, three, and four
?– Merc
Dec 21 '18 at 5:48
@Merc: Indeed, that's how it looks with the Oxford comma. Currently, there are two schools: some people prefer the Oxford comma, while others prefer not to use it. Although I personally always use the Oxford comma, IIRC, Oxford itself has stopped advocating it.
– Andreas Rejbrand
Dec 21 '18 at 12:19
There is something very Oxford about now referring to "The So Recently Oxford Comma".
– jdv
Dec 21 '18 at 15:46
@AndreasRejbrand reference on disuse by Oxford Press? I haven't seen that, and it makes little sense to me. The serial comma seems always clearer, and the challenge of specifying the alternative (e.g. question above) illustrates the consistency of the serial comma.
– Argalatyr
Dec 23 '18 at 12:35