Split an array with commas, except the last item with “and” e.g. (['one', 'two', 'three', 'four'] ->...
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
43 mins ago
You mean I should returnone, two, three, and four
?
– Merc
31 mins 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
asked 2 hours ago
Merc
6,77394785
6,77394785
SURELY you value the serial/Oxford comma?!?
– Argalatyr
43 mins ago
You mean I should returnone, two, three, and four
?
– Merc
31 mins ago
add a comment |
SURELY you value the serial/Oxford comma?!?
– Argalatyr
43 mins ago
You mean I should returnone, two, three, and four
?
– Merc
31 mins ago
SURELY you value the serial/Oxford comma?!?
– Argalatyr
43 mins ago
SURELY you value the serial/Oxford comma?!?
– Argalatyr
43 mins ago
You mean I should return
one, two, three, and four
?– Merc
31 mins ago
You mean I should return
one, two, three, and four
?– Merc
31 mins 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
1 hour ago
1
I love this, and it's just so simple -- especially simple to read (I am a great fan of code maintenance)
– Merc
1 hour 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
1 hour ago
2
Very nice, thought the lack of the Oxford comma is killing me.
– Mark Meyer
1 hour 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
1 hour ago
|
show 1 more comment
You can use Array.prototype.slice()
Code:
const input = ['one', 'two', 'three', 'four'];
const result = `${input.slice(0, -1).join(', ')} and ${input.slice(-1)}`;
console.log(result);
And works with more complex data input = ['A Tale of Two Cities', 'Harry Potter and the smth', 'One Fish, Two Fish, Red Fish, Blue Fish']
Code:
const input = ['A Tale of Two Cities', 'Harry Potter and the smth', 'One Fish, Two Fish, Red Fish, Blue Fish'];
const result = `${input.slice(0, -1).join(', ')} and ${input.slice(-1)}`;
console.log(result);
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
1 hour ago
@user2864740 Good comment, thanks
– Yosvel Quintero
1 hour ago
1
@user2864740 I have updated my answer for that type ofinput
data..
– Yosvel Quintero
1 hour ago
I like this solution a lot. However, if input only has ONE value = 'VALUE', it returns 'and VALUE'
– Merc
23 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%2fsplit-an-array-with-commas-except-the-last-item-with-and-e-g-one-two%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
1 hour ago
1
I love this, and it's just so simple -- especially simple to read (I am a great fan of code maintenance)
– Merc
1 hour 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
1 hour ago
2
Very nice, thought the lack of the Oxford comma is killing me.
– Mark Meyer
1 hour 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
1 hour 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
1 hour ago
1
I love this, and it's just so simple -- especially simple to read (I am a great fan of code maintenance)
– Merc
1 hour 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
1 hour ago
2
Very nice, thought the lack of the Oxford comma is killing me.
– Mark Meyer
1 hour 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
1 hour 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 15 mins ago
answered 2 hours ago
CertainPerformance
73.4k143454
73.4k143454
Might have to be some guards on lengths, and it's the same-same approach I'd probably recommend.
– user2864740
1 hour ago
1
I love this, and it's just so simple -- especially simple to read (I am a great fan of code maintenance)
– Merc
1 hour 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
1 hour ago
2
Very nice, thought the lack of the Oxford comma is killing me.
– Mark Meyer
1 hour 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
1 hour 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
1 hour ago
1
I love this, and it's just so simple -- especially simple to read (I am a great fan of code maintenance)
– Merc
1 hour 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
1 hour ago
2
Very nice, thought the lack of the Oxford comma is killing me.
– Mark Meyer
1 hour 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
1 hour ago
Might have to be some guards on lengths, and it's the same-same approach I'd probably recommend.
– user2864740
1 hour ago
Might have to be some guards on lengths, and it's the same-same approach I'd probably recommend.
– user2864740
1 hour 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
1 hour ago
I love this, and it's just so simple -- especially simple to read (I am a great fan of code maintenance)
– Merc
1 hour 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
1 hour 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
1 hour ago
2
2
Very nice, thought the lack of the Oxford comma is killing me.
– Mark Meyer
1 hour ago
Very nice, thought the lack of the Oxford comma is killing me.
– Mark Meyer
1 hour 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
1 hour 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
1 hour ago
|
show 1 more comment
You can use Array.prototype.slice()
Code:
const input = ['one', 'two', 'three', 'four'];
const result = `${input.slice(0, -1).join(', ')} and ${input.slice(-1)}`;
console.log(result);
And works with more complex data input = ['A Tale of Two Cities', 'Harry Potter and the smth', 'One Fish, Two Fish, Red Fish, Blue Fish']
Code:
const input = ['A Tale of Two Cities', 'Harry Potter and the smth', 'One Fish, Two Fish, Red Fish, Blue Fish'];
const result = `${input.slice(0, -1).join(', ')} and ${input.slice(-1)}`;
console.log(result);
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
1 hour ago
@user2864740 Good comment, thanks
– Yosvel Quintero
1 hour ago
1
@user2864740 I have updated my answer for that type ofinput
data..
– Yosvel Quintero
1 hour ago
I like this solution a lot. However, if input only has ONE value = 'VALUE', it returns 'and VALUE'
– Merc
23 mins ago
add a comment |
You can use Array.prototype.slice()
Code:
const input = ['one', 'two', 'three', 'four'];
const result = `${input.slice(0, -1).join(', ')} and ${input.slice(-1)}`;
console.log(result);
And works with more complex data input = ['A Tale of Two Cities', 'Harry Potter and the smth', 'One Fish, Two Fish, Red Fish, Blue Fish']
Code:
const input = ['A Tale of Two Cities', 'Harry Potter and the smth', 'One Fish, Two Fish, Red Fish, Blue Fish'];
const result = `${input.slice(0, -1).join(', ')} and ${input.slice(-1)}`;
console.log(result);
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
1 hour ago
@user2864740 Good comment, thanks
– Yosvel Quintero
1 hour ago
1
@user2864740 I have updated my answer for that type ofinput
data..
– Yosvel Quintero
1 hour ago
I like this solution a lot. However, if input only has ONE value = 'VALUE', it returns 'and VALUE'
– Merc
23 mins ago
add a comment |
You can use Array.prototype.slice()
Code:
const input = ['one', 'two', 'three', 'four'];
const result = `${input.slice(0, -1).join(', ')} and ${input.slice(-1)}`;
console.log(result);
And works with more complex data input = ['A Tale of Two Cities', 'Harry Potter and the smth', 'One Fish, Two Fish, Red Fish, Blue Fish']
Code:
const input = ['A Tale of Two Cities', 'Harry Potter and the smth', 'One Fish, Two Fish, Red Fish, Blue Fish'];
const result = `${input.slice(0, -1).join(', ')} and ${input.slice(-1)}`;
console.log(result);
You can use Array.prototype.slice()
Code:
const input = ['one', 'two', 'three', 'four'];
const result = `${input.slice(0, -1).join(', ')} and ${input.slice(-1)}`;
console.log(result);
And works with more complex data input = ['A Tale of Two Cities', 'Harry Potter and the smth', 'One Fish, Two Fish, Red Fish, Blue Fish']
Code:
const input = ['A Tale of Two Cities', 'Harry Potter and the smth', 'One Fish, Two Fish, Red Fish, Blue Fish'];
const result = `${input.slice(0, -1).join(', ')} and ${input.slice(-1)}`;
console.log(result);
const input = ['one', 'two', 'three', 'four'];
const result = `${input.slice(0, -1).join(', ')} and ${input.slice(-1)}`;
console.log(result);
const input = ['one', 'two', 'three', 'four'];
const result = `${input.slice(0, -1).join(', ')} and ${input.slice(-1)}`;
console.log(result);
const input = ['A Tale of Two Cities', 'Harry Potter and the smth', 'One Fish, Two Fish, Red Fish, Blue Fish'];
const result = `${input.slice(0, -1).join(', ')} and ${input.slice(-1)}`;
console.log(result);
const input = ['A Tale of Two Cities', 'Harry Potter and the smth', 'One Fish, Two Fish, Red Fish, Blue Fish'];
const result = `${input.slice(0, -1).join(', ')} and ${input.slice(-1)}`;
console.log(result);
edited 1 hour ago
answered 1 hour 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
1 hour ago
@user2864740 Good comment, thanks
– Yosvel Quintero
1 hour ago
1
@user2864740 I have updated my answer for that type ofinput
data..
– Yosvel Quintero
1 hour ago
I like this solution a lot. However, if input only has ONE value = 'VALUE', it returns 'and VALUE'
– Merc
23 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
1 hour ago
@user2864740 Good comment, thanks
– Yosvel Quintero
1 hour ago
1
@user2864740 I have updated my answer for that type ofinput
data..
– Yosvel Quintero
1 hour ago
I like this solution a lot. However, if input only has ONE value = 'VALUE', it returns 'and VALUE'
– Merc
23 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
1 hour 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
1 hour ago
@user2864740 Good comment, thanks
– Yosvel Quintero
1 hour ago
@user2864740 Good comment, thanks
– Yosvel Quintero
1 hour ago
1
1
@user2864740 I have updated my answer for that type of
input
data..– Yosvel Quintero
1 hour ago
@user2864740 I have updated my answer for that type of
input
data..– Yosvel Quintero
1 hour ago
I like this solution a lot. However, if input only has ONE value = 'VALUE', it returns 'and VALUE'
– Merc
23 mins ago
I like this solution a lot. However, if input only has ONE value = 'VALUE', it returns 'and VALUE'
– Merc
23 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 52 mins ago
answered 1 hour ago
Shidersz
3,3011425
3,3011425
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%2fsplit-an-array-with-commas-except-the-last-item-with-and-e-g-one-two%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
43 mins ago
You mean I should return
one, two, three, and four
?– Merc
31 mins ago