Split an array with commas, except the last item with “and” e.g. (['one', 'two', 'three', 'four'] ->...












8














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"...










share|improve this question






















  • 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
















8














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"...










share|improve this question






















  • 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














8












8








8







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"...










share|improve this question













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






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked 2 hours ago









Merc

6,77394785




6,77394785












  • 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


















  • 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
















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












4 Answers
4






active

oldest

votes


















9














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']));








share|improve this answer























  • 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 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



















3














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);








share|improve this answer



















  • 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 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



















2














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());
//








share|improve this answer








New contributor




Jug is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.


























    2














    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(", "));








    share|improve this answer























      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
      });


      }
      });














      draft saved

      draft discarded


















      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









      9














      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']));








      share|improve this answer























      • 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 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
















      9














      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']));








      share|improve this answer























      • 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 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














      9












      9








      9






      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']));








      share|improve this answer














      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']));






      share|improve this answer














      share|improve this answer



      share|improve this answer








      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 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


















      • 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 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
















      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













      3














      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);








      share|improve this answer



















      • 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 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
















      3














      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);








      share|improve this answer



















      • 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 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














      3












      3








      3






      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);








      share|improve this answer














      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);






      share|improve this answer














      share|improve this answer



      share|improve this answer








      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 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














      • 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 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








      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











      2














      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());
      //








      share|improve this answer








      New contributor




      Jug is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.























        2














        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());
        //








        share|improve this answer








        New contributor




        Jug is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
        Check out our Code of Conduct.





















          2












          2








          2






          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());
          //








          share|improve this answer








          New contributor




          Jug is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
          Check out our Code of Conduct.









          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());
          //






          share|improve this answer








          New contributor




          Jug is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
          Check out our Code of Conduct.









          share|improve this answer



          share|improve this answer






          New contributor




          Jug is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
          Check out our Code of Conduct.









          answered 1 hour ago









          Jug

          361




          361




          New contributor




          Jug is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
          Check out our Code of Conduct.





          New contributor





          Jug is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
          Check out our Code of Conduct.






          Jug is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
          Check out our Code of Conduct.























              2














              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(", "));








              share|improve this answer




























                2














                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(", "));








                share|improve this answer


























                  2












                  2








                  2






                  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(", "));








                  share|improve this answer














                  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(", "));






                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited 52 mins ago

























                  answered 1 hour ago









                  Shidersz

                  3,3011425




                  3,3011425






























                      draft saved

                      draft discarded




















































                      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.




                      draft saved


                      draft discarded














                      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





















































                      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







                      Popular posts from this blog

                      サソリ

                      広島県道265号伴広島線

                      Setup Asymptote in Texstudio