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
add a comment |
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
SURELY you value the serial/Oxford comma?!?
– Argalatyr
1 hour ago
You mean I should returnone, two, three, and four
?
– Merc
1 hour ago
add a comment |
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 14 mins ago
Bergi
362k57538861
362k57538861
asked 2 hours ago
Merc
6,77194785
6,77194785
SURELY you value the serial/Oxford comma?!?
– Argalatyr
1 hour ago
You mean I should returnone, two, three, and four
?
– Merc
1 hour ago
add a comment |
SURELY you value the serial/Oxford comma?!?
– Argalatyr
1 hour ago
You mean I should returnone, two, three, and four
?
– Merc
1 hour ago
SURELY you value the serial/Oxford comma?!?
– Argalatyr
1 hour ago
SURELY you value the serial/Oxford comma?!?
– Argalatyr
1 hour ago
You mean I should return
one, two, three, and four
?– Merc
1 hour ago
You mean I should return
one, two, three, and four
?– Merc
1 hour ago
add a comment |
4 Answers
4
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
2 hours ago
1
I love this, and it's just so simple -- especially simple to read (I am a great fan of code maintenance)
– Merc
2 hours ago
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
2 hours ago
2
Very nice, thought the lack of the Oxford comma is killing me.
– Mark Meyer
2 hours ago
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
2 hours ago
|
show 1 more comment
You can use Array.prototype.slice()
Code:
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 = ;
const getResultString = arr => arr && arr.length > 1
? `${arr.slice(0, -1).join(', ')} and ${arr.slice(-1)}`
: arr && arr.length === 1
? arr.toString()
: '';
console.log(getResultString(input1));
console.log(getResultString(input2));
console.log(getResultString(input3));
console.log(getResultString());
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
2 hours ago
@user2864740 Good comment, thanks
– Yosvel Quintero
2 hours ago
1
@user2864740 I have updated my answer for that type ofinput
data..
– Yosvel Quintero
2 hours ago
1
I like this solution a lot. However, if input only has ONE value = 'VALUE', it returns 'and VALUE'
– Merc
1 hour ago
You are right @Merc, I have added validation..
– Yosvel Quintero
25 mins ago
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());
//
New contributor
add a comment |
Another approach could be using the splice method to remove the last two elements of the array and then join they using and
. After this, you could push this result again on the array and finally join using the ,
separator.
let input = ['one', 'two', 'three', 'four'];
let removed = input.splice(-2, 2);
input.push(removed.join(" and "));
console.log(input.join(", "));
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
4 Answers
4
active
oldest
votes
4 Answers
4
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
2 hours ago
1
I love this, and it's just so simple -- especially simple to read (I am a great fan of code maintenance)
– Merc
2 hours ago
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
2 hours ago
2
Very nice, thought the lack of the Oxford comma is killing me.
– Mark Meyer
2 hours ago
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
2 hours ago
|
show 1 more 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
2 hours ago
1
I love this, and it's just so simple -- especially simple to read (I am a great fan of code maintenance)
– Merc
2 hours ago
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
2 hours ago
2
Very nice, thought the lack of the Oxford comma is killing me.
– Mark Meyer
2 hours ago
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
2 hours ago
|
show 1 more 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 58 mins ago
answered 2 hours ago
CertainPerformance
73.4k143455
73.4k143455
Might have to be some guards on lengths, and it's the same-same approach I'd probably recommend.
– user2864740
2 hours ago
1
I love this, and it's just so simple -- especially simple to read (I am a great fan of code maintenance)
– Merc
2 hours ago
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
2 hours ago
2
Very nice, thought the lack of the Oxford comma is killing me.
– Mark Meyer
2 hours ago
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
2 hours ago
|
show 1 more comment
Might have to be some guards on lengths, and it's the same-same approach I'd probably recommend.
– user2864740
2 hours ago
1
I love this, and it's just so simple -- especially simple to read (I am a great fan of code maintenance)
– Merc
2 hours ago
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
2 hours ago
2
Very nice, thought the lack of the Oxford comma is killing me.
– Mark Meyer
2 hours ago
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
2 hours ago
Might have to be some guards on lengths, and it's the same-same approach I'd probably recommend.
– user2864740
2 hours ago
Might have to be some guards on lengths, and it's the same-same approach I'd probably recommend.
– user2864740
2 hours ago
1
1
I love this, and it's just so simple -- especially simple to read (I am a great fan of code maintenance)
– Merc
2 hours ago
I love this, and it's just so simple -- especially simple to read (I am a great fan of code maintenance)
– Merc
2 hours ago
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
2 hours ago
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
2 hours ago
2
2
Very nice, thought the lack of the Oxford comma is killing me.
– Mark Meyer
2 hours ago
Very nice, thought the lack of the Oxford comma is killing me.
– Mark Meyer
2 hours ago
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
2 hours ago
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
2 hours ago
|
show 1 more comment
You can use Array.prototype.slice()
Code:
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 = ;
const getResultString = arr => arr && arr.length > 1
? `${arr.slice(0, -1).join(', ')} and ${arr.slice(-1)}`
: arr && arr.length === 1
? arr.toString()
: '';
console.log(getResultString(input1));
console.log(getResultString(input2));
console.log(getResultString(input3));
console.log(getResultString());
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
2 hours ago
@user2864740 Good comment, thanks
– Yosvel Quintero
2 hours ago
1
@user2864740 I have updated my answer for that type ofinput
data..
– Yosvel Quintero
2 hours ago
1
I like this solution a lot. However, if input only has ONE value = 'VALUE', it returns 'and VALUE'
– Merc
1 hour ago
You are right @Merc, I have added validation..
– Yosvel Quintero
25 mins ago
add a comment |
You can use Array.prototype.slice()
Code:
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 = ;
const getResultString = arr => arr && arr.length > 1
? `${arr.slice(0, -1).join(', ')} and ${arr.slice(-1)}`
: arr && arr.length === 1
? arr.toString()
: '';
console.log(getResultString(input1));
console.log(getResultString(input2));
console.log(getResultString(input3));
console.log(getResultString());
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
2 hours ago
@user2864740 Good comment, thanks
– Yosvel Quintero
2 hours ago
1
@user2864740 I have updated my answer for that type ofinput
data..
– Yosvel Quintero
2 hours ago
1
I like this solution a lot. However, if input only has ONE value = 'VALUE', it returns 'and VALUE'
– Merc
1 hour ago
You are right @Merc, I have added validation..
– Yosvel Quintero
25 mins ago
add a comment |
You can use Array.prototype.slice()
Code:
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 = ;
const getResultString = arr => arr && arr.length > 1
? `${arr.slice(0, -1).join(', ')} and ${arr.slice(-1)}`
: arr && arr.length === 1
? arr.toString()
: '';
console.log(getResultString(input1));
console.log(getResultString(input2));
console.log(getResultString(input3));
console.log(getResultString());
You can use Array.prototype.slice()
Code:
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 = ;
const getResultString = arr => arr && arr.length > 1
? `${arr.slice(0, -1).join(', ')} and ${arr.slice(-1)}`
: arr && arr.length === 1
? arr.toString()
: '';
console.log(getResultString(input1));
console.log(getResultString(input2));
console.log(getResultString(input3));
console.log(getResultString());
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 = ;
const getResultString = arr => arr && arr.length > 1
? `${arr.slice(0, -1).join(', ')} and ${arr.slice(-1)}`
: arr && arr.length === 1
? arr.toString()
: '';
console.log(getResultString(input1));
console.log(getResultString(input2));
console.log(getResultString(input3));
console.log(getResultString());
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 = ;
const getResultString = arr => arr && arr.length > 1
? `${arr.slice(0, -1).join(', ')} and ${arr.slice(-1)}`
: arr && arr.length === 1
? arr.toString()
: '';
console.log(getResultString(input1));
console.log(getResultString(input2));
console.log(getResultString(input3));
console.log(getResultString());
edited 13 mins ago
answered 2 hours ago
Yosvel Quintero
10.9k42229
10.9k42229
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
2 hours ago
@user2864740 Good comment, thanks
– Yosvel Quintero
2 hours ago
1
@user2864740 I have updated my answer for that type ofinput
data..
– Yosvel Quintero
2 hours ago
1
I like this solution a lot. However, if input only has ONE value = 'VALUE', it returns 'and VALUE'
– Merc
1 hour ago
You are right @Merc, I have added validation..
– Yosvel Quintero
25 mins ago
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
2 hours ago
@user2864740 Good comment, thanks
– Yosvel Quintero
2 hours ago
1
@user2864740 I have updated my answer for that type ofinput
data..
– Yosvel Quintero
2 hours ago
1
I like this solution a lot. However, if input only has ONE value = 'VALUE', it returns 'and VALUE'
– Merc
1 hour ago
You are right @Merc, I have added validation..
– Yosvel Quintero
25 mins ago
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
2 hours ago
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
2 hours ago
@user2864740 Good comment, thanks
– Yosvel Quintero
2 hours ago
@user2864740 Good comment, thanks
– Yosvel Quintero
2 hours ago
1
1
@user2864740 I have updated my answer for that type of
input
data..– Yosvel Quintero
2 hours ago
@user2864740 I have updated my answer for that type of
input
data..– Yosvel Quintero
2 hours ago
1
1
I like this solution a lot. However, if input only has ONE value = 'VALUE', it returns 'and VALUE'
– Merc
1 hour ago
I like this solution a lot. However, if input only has ONE value = 'VALUE', it returns 'and VALUE'
– Merc
1 hour ago
You are right @Merc, I have added validation..
– Yosvel Quintero
25 mins ago
You are right @Merc, I have added validation..
– Yosvel Quintero
25 mins ago
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());
//
New contributor
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());
//
New contributor
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());
//
New contributor
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());
//
New contributor
New contributor
answered 1 hour ago
Jug
361
361
New contributor
New contributor
add a comment |
add a comment |
Another approach could be using the splice method to remove the last two elements of the array and then join they using and
. After this, you could push this result again on the array and finally join using the ,
separator.
let input = ['one', 'two', 'three', 'four'];
let removed = input.splice(-2, 2);
input.push(removed.join(" and "));
console.log(input.join(", "));
add a comment |
Another approach could be using the splice method to remove the last two elements of the array and then join they using and
. After this, you could push this result again on the array and finally join using the ,
separator.
let input = ['one', 'two', 'three', 'four'];
let removed = input.splice(-2, 2);
input.push(removed.join(" and "));
console.log(input.join(", "));
add a comment |
Another approach could be using the splice method to remove the last two elements of the array and then join they using and
. After this, you could push this result again on the array and finally join using the ,
separator.
let input = ['one', 'two', 'three', 'four'];
let removed = input.splice(-2, 2);
input.push(removed.join(" and "));
console.log(input.join(", "));
Another approach could be using the splice method to remove the last two elements of the array and then join they using and
. After this, you could push this result again on the array and finally join using the ,
separator.
let input = ['one', 'two', 'three', 'four'];
let removed = input.splice(-2, 2);
input.push(removed.join(" and "));
console.log(input.join(", "));
let input = ['one', 'two', 'three', 'four'];
let removed = input.splice(-2, 2);
input.push(removed.join(" and "));
console.log(input.join(", "));
let input = ['one', 'two', 'three', 'four'];
let removed = input.splice(-2, 2);
input.push(removed.join(" and "));
console.log(input.join(", "));
edited 1 hour ago
answered 2 hours ago
Shidersz
3,3161425
3,3161425
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.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
- 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
SURELY you value the serial/Oxford comma?!?
– Argalatyr
1 hour ago
You mean I should return
one, two, three, and four
?– Merc
1 hour ago