Join an array by commas and “and”












17















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




















  • 14





    SURELY you value the serial/Oxford comma?!?

    – Argalatyr
    Dec 21 '18 at 5:35











  • You mean I should return one, two, three, and four?

    – Merc
    Dec 21 '18 at 5:48











  • @Merc: Indeed, that's how it looks with the Oxford comma. Currently, there are two schools: some people prefer the Oxford comma, while others prefer not to use it. Although I personally always use the Oxford comma, IIRC, Oxford itself has stopped advocating it.

    – Andreas Rejbrand
    Dec 21 '18 at 12:19













  • There is something very Oxford about now referring to "The So Recently Oxford Comma".

    – jdv
    Dec 21 '18 at 15:46













  • @AndreasRejbrand reference on disuse by Oxford Press? I haven't seen that, and it makes little sense to me. The serial comma seems always clearer, and the challenge of specifying the alternative (e.g. question above) illustrates the consistency of the serial comma.

    – Argalatyr
    Dec 23 '18 at 12:35
















17















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




















  • 14





    SURELY you value the serial/Oxford comma?!?

    – Argalatyr
    Dec 21 '18 at 5:35











  • You mean I should return one, two, three, and four?

    – Merc
    Dec 21 '18 at 5:48











  • @Merc: Indeed, that's how it looks with the Oxford comma. Currently, there are two schools: some people prefer the Oxford comma, while others prefer not to use it. Although I personally always use the Oxford comma, IIRC, Oxford itself has stopped advocating it.

    – Andreas Rejbrand
    Dec 21 '18 at 12:19













  • There is something very Oxford about now referring to "The So Recently Oxford Comma".

    – jdv
    Dec 21 '18 at 15:46













  • @AndreasRejbrand reference on disuse by Oxford Press? I haven't seen that, and it makes little sense to me. The serial comma seems always clearer, and the challenge of specifying the alternative (e.g. question above) illustrates the consistency of the serial comma.

    – Argalatyr
    Dec 23 '18 at 12:35














17












17








17


0






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








edited Dec 21 '18 at 6:48









Bergi

366k58546872




366k58546872










asked Dec 21 '18 at 4:15









MercMerc

6,91294788




6,91294788








  • 14





    SURELY you value the serial/Oxford comma?!?

    – Argalatyr
    Dec 21 '18 at 5:35











  • You mean I should return one, two, three, and four?

    – Merc
    Dec 21 '18 at 5:48











  • @Merc: Indeed, that's how it looks with the Oxford comma. Currently, there are two schools: some people prefer the Oxford comma, while others prefer not to use it. Although I personally always use the Oxford comma, IIRC, Oxford itself has stopped advocating it.

    – Andreas Rejbrand
    Dec 21 '18 at 12:19













  • There is something very Oxford about now referring to "The So Recently Oxford Comma".

    – jdv
    Dec 21 '18 at 15:46













  • @AndreasRejbrand reference on disuse by Oxford Press? I haven't seen that, and it makes little sense to me. The serial comma seems always clearer, and the challenge of specifying the alternative (e.g. question above) illustrates the consistency of the serial comma.

    – Argalatyr
    Dec 23 '18 at 12:35














  • 14





    SURELY you value the serial/Oxford comma?!?

    – Argalatyr
    Dec 21 '18 at 5:35











  • You mean I should return one, two, three, and four?

    – Merc
    Dec 21 '18 at 5:48











  • @Merc: Indeed, that's how it looks with the Oxford comma. Currently, there are two schools: some people prefer the Oxford comma, while others prefer not to use it. Although I personally always use the Oxford comma, IIRC, Oxford itself has stopped advocating it.

    – Andreas Rejbrand
    Dec 21 '18 at 12:19













  • There is something very Oxford about now referring to "The So Recently Oxford Comma".

    – jdv
    Dec 21 '18 at 15:46













  • @AndreasRejbrand reference on disuse by Oxford Press? I haven't seen that, and it makes little sense to me. The serial comma seems always clearer, and the challenge of specifying the alternative (e.g. question above) illustrates the consistency of the serial comma.

    – Argalatyr
    Dec 23 '18 at 12:35








14




14





SURELY you value the serial/Oxford comma?!?

– Argalatyr
Dec 21 '18 at 5:35





SURELY you value the serial/Oxford comma?!?

– Argalatyr
Dec 21 '18 at 5:35













You mean I should return one, two, three, and four?

– Merc
Dec 21 '18 at 5:48





You mean I should return one, two, three, and four?

– Merc
Dec 21 '18 at 5:48













@Merc: Indeed, that's how it looks with the Oxford comma. Currently, there are two schools: some people prefer the Oxford comma, while others prefer not to use it. Although I personally always use the Oxford comma, IIRC, Oxford itself has stopped advocating it.

– Andreas Rejbrand
Dec 21 '18 at 12:19







@Merc: Indeed, that's how it looks with the Oxford comma. Currently, there are two schools: some people prefer the Oxford comma, while others prefer not to use it. Although I personally always use the Oxford comma, IIRC, Oxford itself has stopped advocating it.

– Andreas Rejbrand
Dec 21 '18 at 12:19















There is something very Oxford about now referring to "The So Recently Oxford Comma".

– jdv
Dec 21 '18 at 15:46







There is something very Oxford about now referring to "The So Recently Oxford Comma".

– jdv
Dec 21 '18 at 15:46















@AndreasRejbrand reference on disuse by Oxford Press? I haven't seen that, and it makes little sense to me. The serial comma seems always clearer, and the challenge of specifying the alternative (e.g. question above) illustrates the consistency of the serial comma.

– Argalatyr
Dec 23 '18 at 12:35





@AndreasRejbrand reference on disuse by Oxford Press? I haven't seen that, and it makes little sense to me. The serial comma seems always clearer, and the challenge of specifying the alternative (e.g. question above) illustrates the consistency of the serial comma.

– Argalatyr
Dec 23 '18 at 12:35












6 Answers
6






active

oldest

votes


















23














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
    Dec 21 '18 at 4:22






  • 1





    I love this, and it's just so simple -- especially simple to read (I am a great fan of code maintenance)

    – Merc
    Dec 21 '18 at 4:25











  • I think this is hard to beat, but I am waiting a little before accepting in case it attracts even better answers. But, I love it

    – Merc
    Dec 21 '18 at 4:26






  • 6





    Very nice, thought the lack of the Oxford comma is killing me.

    – Mark Meyer
    Dec 21 '18 at 4:43











  • As an echo to an other answer, you may want to push last back in input (you know, "modifying the inputs when it's not the output is bad" and stuff like that...)

    – Kaiido
    Dec 21 '18 at 4:53



















12














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































    8














    Starting in V8 v7.2 and Chrome 72, you can use the sweet Intl.ListFormat API. It will also take care of localizing your list when requested, which might be of great help if you need it.






    const lf = new Intl.ListFormat('en');
    lf.format(['Frank']);
    // → 'Frank'
    lf.format(['Frank', 'Christine']);
    // → 'Frank and Christine'
    lf.format(['Frank', 'Christine', 'Flora']);
    // → 'Frank, Christine, and Flora'
    lf.format(['Frank', 'Christine', 'Flora', 'Harrison']);
    // → 'Frank, Christine, Flora, and Harrison'





    You can even specify options to make it a disruption and use "or" instead of "and", or to format units such as "3 ft, 7 in".



    References
    The Intl.ListFormat API - Google Developers
    V8 release v7.2






    share|improve this answer































      7














      You can use Array.prototype.slice() when array.length is bigger than 1 and exclude the rest of the cases:



      a.length > 1 ? `${a.slice(0, -1).join(', ')} and ${a.slice(-1)}` : {0: '', 1: a[0]}[a.length]


      Code example:






      const input1 = ['one', 'two', 'three', 'four'];
      const input2 = ['A Tale of Two Cities', 'Harry Potter and the smth', 'One Fish, Two Fish, Red Fish, Blue Fish'];
      const input3 = ['one', 'two'];
      const input4 = ['one'];
      const input5 = ;

      const result = a => a.length > 1
      ? `${a.slice(0, -1).join(', ')} and ${a.slice(-1)}`
      : {0: '', 1: a[0]}[a.length];

      console.log(result(input1));
      console.log(result(input2));
      console.log(result(input3));
      console.log(result(input4));
      console.log(result(input5));








      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
        Dec 21 '18 at 4:23













      • @user2864740 Good comment, thanks

        – Yosvel Quintero
        Dec 21 '18 at 4:24






      • 1





        @user2864740 I have updated my answer for that type of input data..

        – Yosvel Quintero
        Dec 21 '18 at 4:39






      • 1





        I like this solution a lot. However, if input only has ONE value = 'VALUE', it returns 'and VALUE'

        – Merc
        Dec 21 '18 at 5:55











      • You are right @Merc, I have added validation..

        – Yosvel Quintero
        Dec 21 '18 at 6:37



















      3














      Another approach could be using the splice method to remove the last two elements of the array and join they using the and token. After this, you could push this result again on the array, and finally join all elements using the , separator.





      Updated to:



      1) Show how this works for multiple cases (no extra control needed over the array length).



      2) Wrap the logic inside a method.



      3) Do not mutate the original array (if not required).






      let arrayToCustomStr = (arr, enableMutate) =>
      {
      // Clone the received array (if required).
      let a = enableMutate ? arr : arr.slice(0);

      // Convert the array to custom string.
      let removed = a.splice(-2, 2);
      a.push(removed.join(" and "));
      return a.join(", ");
      }

      // First example, mutate of original array is disabled.
      let input1 = ['one', 'two', 'three', 'four'];
      console.log("Result for input1:" , arrayToCustomStr(input1));
      console.log("Original input1:", input1);

      // Second example, mutate of original array is enabled.
      let input2 = ['one', 'two'];
      console.log("Result for input2:", arrayToCustomStr(input2, true));
      console.log("Original input2:", input2);

      // Third example, lenght of array is 1.
      let input3 = ['one'];
      console.log("Result for input3:", arrayToCustomStr(input3));

      // Fourth example, empty array.
      let input4 = ;
      console.log("Result for input4:", arrayToCustomStr(input4));

      // Plus example.
      let bob = [
      "Don't worry about a thing",
      "Cause every little thing",
      "Gonna be all right",
      "Saying, don't worry about a thing..."
      ];
      console.log("Result for bob:", arrayToCustomStr(bob));

      .as-console-wrapper {
      top: 0px;
      max-height: 100% !important;
      }








      share|improve this answer

































        1














        Using Array#reduce:



        ['one', 'two', 'three', 'four'].reduce(
        (a, b, i, array) => a + (i < array.length - 1 ? ', ' : ' and ') + b)






        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%2fjoin-an-array-by-commas-and-and%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          6 Answers
          6






          active

          oldest

          votes








          6 Answers
          6






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          23














          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
            Dec 21 '18 at 4:22






          • 1





            I love this, and it's just so simple -- especially simple to read (I am a great fan of code maintenance)

            – Merc
            Dec 21 '18 at 4:25











          • I think this is hard to beat, but I am waiting a little before accepting in case it attracts even better answers. But, I love it

            – Merc
            Dec 21 '18 at 4:26






          • 6





            Very nice, thought the lack of the Oxford comma is killing me.

            – Mark Meyer
            Dec 21 '18 at 4:43











          • As an echo to an other answer, you may want to push last back in input (you know, "modifying the inputs when it's not the output is bad" and stuff like that...)

            – Kaiido
            Dec 21 '18 at 4:53
















          23














          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
            Dec 21 '18 at 4:22






          • 1





            I love this, and it's just so simple -- especially simple to read (I am a great fan of code maintenance)

            – Merc
            Dec 21 '18 at 4:25











          • I think this is hard to beat, but I am waiting a little before accepting in case it attracts even better answers. But, I love it

            – Merc
            Dec 21 '18 at 4:26






          • 6





            Very nice, thought the lack of the Oxford comma is killing me.

            – Mark Meyer
            Dec 21 '18 at 4:43











          • As an echo to an other answer, you may want to push last back in input (you know, "modifying the inputs when it's not the output is bad" and stuff like that...)

            – Kaiido
            Dec 21 '18 at 4:53














          23












          23








          23







          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 Dec 21 '18 at 6:04

























          answered Dec 21 '18 at 4:17









          CertainPerformanceCertainPerformance

          80.3k143865




          80.3k143865













          • Might have to be some guards on lengths, and it's the same-same approach I'd probably recommend.

            – user2864740
            Dec 21 '18 at 4:22






          • 1





            I love this, and it's just so simple -- especially simple to read (I am a great fan of code maintenance)

            – Merc
            Dec 21 '18 at 4:25











          • I think this is hard to beat, but I am waiting a little before accepting in case it attracts even better answers. But, I love it

            – Merc
            Dec 21 '18 at 4:26






          • 6





            Very nice, thought the lack of the Oxford comma is killing me.

            – Mark Meyer
            Dec 21 '18 at 4:43











          • As an echo to an other answer, you may want to push last back in input (you know, "modifying the inputs when it's not the output is bad" and stuff like that...)

            – Kaiido
            Dec 21 '18 at 4:53



















          • Might have to be some guards on lengths, and it's the same-same approach I'd probably recommend.

            – user2864740
            Dec 21 '18 at 4:22






          • 1





            I love this, and it's just so simple -- especially simple to read (I am a great fan of code maintenance)

            – Merc
            Dec 21 '18 at 4:25











          • I think this is hard to beat, but I am waiting a little before accepting in case it attracts even better answers. But, I love it

            – Merc
            Dec 21 '18 at 4:26






          • 6





            Very nice, thought the lack of the Oxford comma is killing me.

            – Mark Meyer
            Dec 21 '18 at 4:43











          • As an echo to an other answer, you may want to push last back in input (you know, "modifying the inputs when it's not the output is bad" and stuff like that...)

            – Kaiido
            Dec 21 '18 at 4:53

















          Might have to be some guards on lengths, and it's the same-same approach I'd probably recommend.

          – user2864740
          Dec 21 '18 at 4:22





          Might have to be some guards on lengths, and it's the same-same approach I'd probably recommend.

          – user2864740
          Dec 21 '18 at 4:22




          1




          1





          I love this, and it's just so simple -- especially simple to read (I am a great fan of code maintenance)

          – Merc
          Dec 21 '18 at 4:25





          I love this, and it's just so simple -- especially simple to read (I am a great fan of code maintenance)

          – Merc
          Dec 21 '18 at 4:25













          I think this is hard to beat, but I am waiting a little before accepting in case it attracts even better answers. But, I love it

          – Merc
          Dec 21 '18 at 4:26





          I think this is hard to beat, but I am waiting a little before accepting in case it attracts even better answers. But, I love it

          – Merc
          Dec 21 '18 at 4:26




          6




          6





          Very nice, thought the lack of the Oxford comma is killing me.

          – Mark Meyer
          Dec 21 '18 at 4:43





          Very nice, thought the lack of the Oxford comma is killing me.

          – Mark Meyer
          Dec 21 '18 at 4:43













          As an echo to an other answer, you may want to push last back in input (you know, "modifying the inputs when it's not the output is bad" and stuff like that...)

          – Kaiido
          Dec 21 '18 at 4:53





          As an echo to an other answer, you may want to push last back in input (you know, "modifying the inputs when it's not the output is bad" and stuff like that...)

          – Kaiido
          Dec 21 '18 at 4:53













          12














          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




























            12














            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


























              12












              12








              12







              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













              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












              share|improve this answer



              share|improve this answer










              answered Dec 21 '18 at 5:18









              JugJug

              1362




              1362























                  8














                  Starting in V8 v7.2 and Chrome 72, you can use the sweet Intl.ListFormat API. It will also take care of localizing your list when requested, which might be of great help if you need it.






                  const lf = new Intl.ListFormat('en');
                  lf.format(['Frank']);
                  // → 'Frank'
                  lf.format(['Frank', 'Christine']);
                  // → 'Frank and Christine'
                  lf.format(['Frank', 'Christine', 'Flora']);
                  // → 'Frank, Christine, and Flora'
                  lf.format(['Frank', 'Christine', 'Flora', 'Harrison']);
                  // → 'Frank, Christine, Flora, and Harrison'





                  You can even specify options to make it a disruption and use "or" instead of "and", or to format units such as "3 ft, 7 in".



                  References
                  The Intl.ListFormat API - Google Developers
                  V8 release v7.2






                  share|improve this answer




























                    8














                    Starting in V8 v7.2 and Chrome 72, you can use the sweet Intl.ListFormat API. It will also take care of localizing your list when requested, which might be of great help if you need it.






                    const lf = new Intl.ListFormat('en');
                    lf.format(['Frank']);
                    // → 'Frank'
                    lf.format(['Frank', 'Christine']);
                    // → 'Frank and Christine'
                    lf.format(['Frank', 'Christine', 'Flora']);
                    // → 'Frank, Christine, and Flora'
                    lf.format(['Frank', 'Christine', 'Flora', 'Harrison']);
                    // → 'Frank, Christine, Flora, and Harrison'





                    You can even specify options to make it a disruption and use "or" instead of "and", or to format units such as "3 ft, 7 in".



                    References
                    The Intl.ListFormat API - Google Developers
                    V8 release v7.2






                    share|improve this answer


























                      8












                      8








                      8







                      Starting in V8 v7.2 and Chrome 72, you can use the sweet Intl.ListFormat API. It will also take care of localizing your list when requested, which might be of great help if you need it.






                      const lf = new Intl.ListFormat('en');
                      lf.format(['Frank']);
                      // → 'Frank'
                      lf.format(['Frank', 'Christine']);
                      // → 'Frank and Christine'
                      lf.format(['Frank', 'Christine', 'Flora']);
                      // → 'Frank, Christine, and Flora'
                      lf.format(['Frank', 'Christine', 'Flora', 'Harrison']);
                      // → 'Frank, Christine, Flora, and Harrison'





                      You can even specify options to make it a disruption and use "or" instead of "and", or to format units such as "3 ft, 7 in".



                      References
                      The Intl.ListFormat API - Google Developers
                      V8 release v7.2






                      share|improve this answer













                      Starting in V8 v7.2 and Chrome 72, you can use the sweet Intl.ListFormat API. It will also take care of localizing your list when requested, which might be of great help if you need it.






                      const lf = new Intl.ListFormat('en');
                      lf.format(['Frank']);
                      // → 'Frank'
                      lf.format(['Frank', 'Christine']);
                      // → 'Frank and Christine'
                      lf.format(['Frank', 'Christine', 'Flora']);
                      // → 'Frank, Christine, and Flora'
                      lf.format(['Frank', 'Christine', 'Flora', 'Harrison']);
                      // → 'Frank, Christine, Flora, and Harrison'





                      You can even specify options to make it a disruption and use "or" instead of "and", or to format units such as "3 ft, 7 in".



                      References
                      The Intl.ListFormat API - Google Developers
                      V8 release v7.2






                      const lf = new Intl.ListFormat('en');
                      lf.format(['Frank']);
                      // → 'Frank'
                      lf.format(['Frank', 'Christine']);
                      // → 'Frank and Christine'
                      lf.format(['Frank', 'Christine', 'Flora']);
                      // → 'Frank, Christine, and Flora'
                      lf.format(['Frank', 'Christine', 'Flora', 'Harrison']);
                      // → 'Frank, Christine, Flora, and Harrison'





                      const lf = new Intl.ListFormat('en');
                      lf.format(['Frank']);
                      // → 'Frank'
                      lf.format(['Frank', 'Christine']);
                      // → 'Frank and Christine'
                      lf.format(['Frank', 'Christine', 'Flora']);
                      // → 'Frank, Christine, and Flora'
                      lf.format(['Frank', 'Christine', 'Flora', 'Harrison']);
                      // → 'Frank, Christine, Flora, and Harrison'






                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered Dec 21 '18 at 11:08









                      Baptiste CandellierBaptiste Candellier

                      29629




                      29629























                          7














                          You can use Array.prototype.slice() when array.length is bigger than 1 and exclude the rest of the cases:



                          a.length > 1 ? `${a.slice(0, -1).join(', ')} and ${a.slice(-1)}` : {0: '', 1: a[0]}[a.length]


                          Code example:






                          const input1 = ['one', 'two', 'three', 'four'];
                          const input2 = ['A Tale of Two Cities', 'Harry Potter and the smth', 'One Fish, Two Fish, Red Fish, Blue Fish'];
                          const input3 = ['one', 'two'];
                          const input4 = ['one'];
                          const input5 = ;

                          const result = a => a.length > 1
                          ? `${a.slice(0, -1).join(', ')} and ${a.slice(-1)}`
                          : {0: '', 1: a[0]}[a.length];

                          console.log(result(input1));
                          console.log(result(input2));
                          console.log(result(input3));
                          console.log(result(input4));
                          console.log(result(input5));








                          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
                            Dec 21 '18 at 4:23













                          • @user2864740 Good comment, thanks

                            – Yosvel Quintero
                            Dec 21 '18 at 4:24






                          • 1





                            @user2864740 I have updated my answer for that type of input data..

                            – Yosvel Quintero
                            Dec 21 '18 at 4:39






                          • 1





                            I like this solution a lot. However, if input only has ONE value = 'VALUE', it returns 'and VALUE'

                            – Merc
                            Dec 21 '18 at 5:55











                          • You are right @Merc, I have added validation..

                            – Yosvel Quintero
                            Dec 21 '18 at 6:37
















                          7














                          You can use Array.prototype.slice() when array.length is bigger than 1 and exclude the rest of the cases:



                          a.length > 1 ? `${a.slice(0, -1).join(', ')} and ${a.slice(-1)}` : {0: '', 1: a[0]}[a.length]


                          Code example:






                          const input1 = ['one', 'two', 'three', 'four'];
                          const input2 = ['A Tale of Two Cities', 'Harry Potter and the smth', 'One Fish, Two Fish, Red Fish, Blue Fish'];
                          const input3 = ['one', 'two'];
                          const input4 = ['one'];
                          const input5 = ;

                          const result = a => a.length > 1
                          ? `${a.slice(0, -1).join(', ')} and ${a.slice(-1)}`
                          : {0: '', 1: a[0]}[a.length];

                          console.log(result(input1));
                          console.log(result(input2));
                          console.log(result(input3));
                          console.log(result(input4));
                          console.log(result(input5));








                          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
                            Dec 21 '18 at 4:23













                          • @user2864740 Good comment, thanks

                            – Yosvel Quintero
                            Dec 21 '18 at 4:24






                          • 1





                            @user2864740 I have updated my answer for that type of input data..

                            – Yosvel Quintero
                            Dec 21 '18 at 4:39






                          • 1





                            I like this solution a lot. However, if input only has ONE value = 'VALUE', it returns 'and VALUE'

                            – Merc
                            Dec 21 '18 at 5:55











                          • You are right @Merc, I have added validation..

                            – Yosvel Quintero
                            Dec 21 '18 at 6:37














                          7












                          7








                          7







                          You can use Array.prototype.slice() when array.length is bigger than 1 and exclude the rest of the cases:



                          a.length > 1 ? `${a.slice(0, -1).join(', ')} and ${a.slice(-1)}` : {0: '', 1: a[0]}[a.length]


                          Code example:






                          const input1 = ['one', 'two', 'three', 'four'];
                          const input2 = ['A Tale of Two Cities', 'Harry Potter and the smth', 'One Fish, Two Fish, Red Fish, Blue Fish'];
                          const input3 = ['one', 'two'];
                          const input4 = ['one'];
                          const input5 = ;

                          const result = a => a.length > 1
                          ? `${a.slice(0, -1).join(', ')} and ${a.slice(-1)}`
                          : {0: '', 1: a[0]}[a.length];

                          console.log(result(input1));
                          console.log(result(input2));
                          console.log(result(input3));
                          console.log(result(input4));
                          console.log(result(input5));








                          share|improve this answer















                          You can use Array.prototype.slice() when array.length is bigger than 1 and exclude the rest of the cases:



                          a.length > 1 ? `${a.slice(0, -1).join(', ')} and ${a.slice(-1)}` : {0: '', 1: a[0]}[a.length]


                          Code example:






                          const input1 = ['one', 'two', 'three', 'four'];
                          const input2 = ['A Tale of Two Cities', 'Harry Potter and the smth', 'One Fish, Two Fish, Red Fish, Blue Fish'];
                          const input3 = ['one', 'two'];
                          const input4 = ['one'];
                          const input5 = ;

                          const result = a => a.length > 1
                          ? `${a.slice(0, -1).join(', ')} and ${a.slice(-1)}`
                          : {0: '', 1: a[0]}[a.length];

                          console.log(result(input1));
                          console.log(result(input2));
                          console.log(result(input3));
                          console.log(result(input4));
                          console.log(result(input5));








                          const input1 = ['one', 'two', 'three', 'four'];
                          const input2 = ['A Tale of Two Cities', 'Harry Potter and the smth', 'One Fish, Two Fish, Red Fish, Blue Fish'];
                          const input3 = ['one', 'two'];
                          const input4 = ['one'];
                          const input5 = ;

                          const result = a => a.length > 1
                          ? `${a.slice(0, -1).join(', ')} and ${a.slice(-1)}`
                          : {0: '', 1: a[0]}[a.length];

                          console.log(result(input1));
                          console.log(result(input2));
                          console.log(result(input3));
                          console.log(result(input4));
                          console.log(result(input5));





                          const input1 = ['one', 'two', 'three', 'four'];
                          const input2 = ['A Tale of Two Cities', 'Harry Potter and the smth', 'One Fish, Two Fish, Red Fish, Blue Fish'];
                          const input3 = ['one', 'two'];
                          const input4 = ['one'];
                          const input5 = ;

                          const result = a => a.length > 1
                          ? `${a.slice(0, -1).join(', ')} and ${a.slice(-1)}`
                          : {0: '', 1: a[0]}[a.length];

                          console.log(result(input1));
                          console.log(result(input2));
                          console.log(result(input3));
                          console.log(result(input4));
                          console.log(result(input5));






                          share|improve this answer














                          share|improve this answer



                          share|improve this answer








                          edited Dec 23 '18 at 2:07

























                          answered Dec 21 '18 at 4:21









                          Yosvel QuinteroYosvel Quintero

                          11k42329




                          11k42329








                          • 1





                            Easy to introduce subtle issues that'll be found later (outside of a restricted set of input): ['A Tale of Two Cities', 'Harry Potter and the smth', 'One Fish, Two Fish, Red Fish, Blue Fish']

                            – user2864740
                            Dec 21 '18 at 4:23













                          • @user2864740 Good comment, thanks

                            – Yosvel Quintero
                            Dec 21 '18 at 4:24






                          • 1





                            @user2864740 I have updated my answer for that type of input data..

                            – Yosvel Quintero
                            Dec 21 '18 at 4:39






                          • 1





                            I like this solution a lot. However, if input only has ONE value = 'VALUE', it returns 'and VALUE'

                            – Merc
                            Dec 21 '18 at 5:55











                          • You are right @Merc, I have added validation..

                            – Yosvel Quintero
                            Dec 21 '18 at 6:37














                          • 1





                            Easy to introduce subtle issues that'll be found later (outside of a restricted set of input): ['A Tale of Two Cities', 'Harry Potter and the smth', 'One Fish, Two Fish, Red Fish, Blue Fish']

                            – user2864740
                            Dec 21 '18 at 4:23













                          • @user2864740 Good comment, thanks

                            – Yosvel Quintero
                            Dec 21 '18 at 4:24






                          • 1





                            @user2864740 I have updated my answer for that type of input data..

                            – Yosvel Quintero
                            Dec 21 '18 at 4:39






                          • 1





                            I like this solution a lot. However, if input only has ONE value = 'VALUE', it returns 'and VALUE'

                            – Merc
                            Dec 21 '18 at 5:55











                          • You are right @Merc, I have added validation..

                            – Yosvel Quintero
                            Dec 21 '18 at 6:37








                          1




                          1





                          Easy to introduce subtle issues that'll be found later (outside of a restricted set of input): ['A Tale of Two Cities', 'Harry Potter and the smth', 'One Fish, Two Fish, Red Fish, Blue Fish']

                          – user2864740
                          Dec 21 '18 at 4:23







                          Easy to introduce subtle issues that'll be found later (outside of a restricted set of input): ['A Tale of Two Cities', 'Harry Potter and the smth', 'One Fish, Two Fish, Red Fish, Blue Fish']

                          – user2864740
                          Dec 21 '18 at 4:23















                          @user2864740 Good comment, thanks

                          – Yosvel Quintero
                          Dec 21 '18 at 4:24





                          @user2864740 Good comment, thanks

                          – Yosvel Quintero
                          Dec 21 '18 at 4:24




                          1




                          1





                          @user2864740 I have updated my answer for that type of input data..

                          – Yosvel Quintero
                          Dec 21 '18 at 4:39





                          @user2864740 I have updated my answer for that type of input data..

                          – Yosvel Quintero
                          Dec 21 '18 at 4:39




                          1




                          1





                          I like this solution a lot. However, if input only has ONE value = 'VALUE', it returns 'and VALUE'

                          – Merc
                          Dec 21 '18 at 5:55





                          I like this solution a lot. However, if input only has ONE value = 'VALUE', it returns 'and VALUE'

                          – Merc
                          Dec 21 '18 at 5:55













                          You are right @Merc, I have added validation..

                          – Yosvel Quintero
                          Dec 21 '18 at 6:37





                          You are right @Merc, I have added validation..

                          – Yosvel Quintero
                          Dec 21 '18 at 6:37











                          3














                          Another approach could be using the splice method to remove the last two elements of the array and join they using the and token. After this, you could push this result again on the array, and finally join all elements using the , separator.





                          Updated to:



                          1) Show how this works for multiple cases (no extra control needed over the array length).



                          2) Wrap the logic inside a method.



                          3) Do not mutate the original array (if not required).






                          let arrayToCustomStr = (arr, enableMutate) =>
                          {
                          // Clone the received array (if required).
                          let a = enableMutate ? arr : arr.slice(0);

                          // Convert the array to custom string.
                          let removed = a.splice(-2, 2);
                          a.push(removed.join(" and "));
                          return a.join(", ");
                          }

                          // First example, mutate of original array is disabled.
                          let input1 = ['one', 'two', 'three', 'four'];
                          console.log("Result for input1:" , arrayToCustomStr(input1));
                          console.log("Original input1:", input1);

                          // Second example, mutate of original array is enabled.
                          let input2 = ['one', 'two'];
                          console.log("Result for input2:", arrayToCustomStr(input2, true));
                          console.log("Original input2:", input2);

                          // Third example, lenght of array is 1.
                          let input3 = ['one'];
                          console.log("Result for input3:", arrayToCustomStr(input3));

                          // Fourth example, empty array.
                          let input4 = ;
                          console.log("Result for input4:", arrayToCustomStr(input4));

                          // Plus example.
                          let bob = [
                          "Don't worry about a thing",
                          "Cause every little thing",
                          "Gonna be all right",
                          "Saying, don't worry about a thing..."
                          ];
                          console.log("Result for bob:", arrayToCustomStr(bob));

                          .as-console-wrapper {
                          top: 0px;
                          max-height: 100% !important;
                          }








                          share|improve this answer






























                            3














                            Another approach could be using the splice method to remove the last two elements of the array and join they using the and token. After this, you could push this result again on the array, and finally join all elements using the , separator.





                            Updated to:



                            1) Show how this works for multiple cases (no extra control needed over the array length).



                            2) Wrap the logic inside a method.



                            3) Do not mutate the original array (if not required).






                            let arrayToCustomStr = (arr, enableMutate) =>
                            {
                            // Clone the received array (if required).
                            let a = enableMutate ? arr : arr.slice(0);

                            // Convert the array to custom string.
                            let removed = a.splice(-2, 2);
                            a.push(removed.join(" and "));
                            return a.join(", ");
                            }

                            // First example, mutate of original array is disabled.
                            let input1 = ['one', 'two', 'three', 'four'];
                            console.log("Result for input1:" , arrayToCustomStr(input1));
                            console.log("Original input1:", input1);

                            // Second example, mutate of original array is enabled.
                            let input2 = ['one', 'two'];
                            console.log("Result for input2:", arrayToCustomStr(input2, true));
                            console.log("Original input2:", input2);

                            // Third example, lenght of array is 1.
                            let input3 = ['one'];
                            console.log("Result for input3:", arrayToCustomStr(input3));

                            // Fourth example, empty array.
                            let input4 = ;
                            console.log("Result for input4:", arrayToCustomStr(input4));

                            // Plus example.
                            let bob = [
                            "Don't worry about a thing",
                            "Cause every little thing",
                            "Gonna be all right",
                            "Saying, don't worry about a thing..."
                            ];
                            console.log("Result for bob:", arrayToCustomStr(bob));

                            .as-console-wrapper {
                            top: 0px;
                            max-height: 100% !important;
                            }








                            share|improve this answer




























                              3












                              3








                              3







                              Another approach could be using the splice method to remove the last two elements of the array and join they using the and token. After this, you could push this result again on the array, and finally join all elements using the , separator.





                              Updated to:



                              1) Show how this works for multiple cases (no extra control needed over the array length).



                              2) Wrap the logic inside a method.



                              3) Do not mutate the original array (if not required).






                              let arrayToCustomStr = (arr, enableMutate) =>
                              {
                              // Clone the received array (if required).
                              let a = enableMutate ? arr : arr.slice(0);

                              // Convert the array to custom string.
                              let removed = a.splice(-2, 2);
                              a.push(removed.join(" and "));
                              return a.join(", ");
                              }

                              // First example, mutate of original array is disabled.
                              let input1 = ['one', 'two', 'three', 'four'];
                              console.log("Result for input1:" , arrayToCustomStr(input1));
                              console.log("Original input1:", input1);

                              // Second example, mutate of original array is enabled.
                              let input2 = ['one', 'two'];
                              console.log("Result for input2:", arrayToCustomStr(input2, true));
                              console.log("Original input2:", input2);

                              // Third example, lenght of array is 1.
                              let input3 = ['one'];
                              console.log("Result for input3:", arrayToCustomStr(input3));

                              // Fourth example, empty array.
                              let input4 = ;
                              console.log("Result for input4:", arrayToCustomStr(input4));

                              // Plus example.
                              let bob = [
                              "Don't worry about a thing",
                              "Cause every little thing",
                              "Gonna be all right",
                              "Saying, don't worry about a thing..."
                              ];
                              console.log("Result for bob:", arrayToCustomStr(bob));

                              .as-console-wrapper {
                              top: 0px;
                              max-height: 100% !important;
                              }








                              share|improve this answer















                              Another approach could be using the splice method to remove the last two elements of the array and join they using the and token. After this, you could push this result again on the array, and finally join all elements using the , separator.





                              Updated to:



                              1) Show how this works for multiple cases (no extra control needed over the array length).



                              2) Wrap the logic inside a method.



                              3) Do not mutate the original array (if not required).






                              let arrayToCustomStr = (arr, enableMutate) =>
                              {
                              // Clone the received array (if required).
                              let a = enableMutate ? arr : arr.slice(0);

                              // Convert the array to custom string.
                              let removed = a.splice(-2, 2);
                              a.push(removed.join(" and "));
                              return a.join(", ");
                              }

                              // First example, mutate of original array is disabled.
                              let input1 = ['one', 'two', 'three', 'four'];
                              console.log("Result for input1:" , arrayToCustomStr(input1));
                              console.log("Original input1:", input1);

                              // Second example, mutate of original array is enabled.
                              let input2 = ['one', 'two'];
                              console.log("Result for input2:", arrayToCustomStr(input2, true));
                              console.log("Original input2:", input2);

                              // Third example, lenght of array is 1.
                              let input3 = ['one'];
                              console.log("Result for input3:", arrayToCustomStr(input3));

                              // Fourth example, empty array.
                              let input4 = ;
                              console.log("Result for input4:", arrayToCustomStr(input4));

                              // Plus example.
                              let bob = [
                              "Don't worry about a thing",
                              "Cause every little thing",
                              "Gonna be all right",
                              "Saying, don't worry about a thing..."
                              ];
                              console.log("Result for bob:", arrayToCustomStr(bob));

                              .as-console-wrapper {
                              top: 0px;
                              max-height: 100% !important;
                              }








                              let arrayToCustomStr = (arr, enableMutate) =>
                              {
                              // Clone the received array (if required).
                              let a = enableMutate ? arr : arr.slice(0);

                              // Convert the array to custom string.
                              let removed = a.splice(-2, 2);
                              a.push(removed.join(" and "));
                              return a.join(", ");
                              }

                              // First example, mutate of original array is disabled.
                              let input1 = ['one', 'two', 'three', 'four'];
                              console.log("Result for input1:" , arrayToCustomStr(input1));
                              console.log("Original input1:", input1);

                              // Second example, mutate of original array is enabled.
                              let input2 = ['one', 'two'];
                              console.log("Result for input2:", arrayToCustomStr(input2, true));
                              console.log("Original input2:", input2);

                              // Third example, lenght of array is 1.
                              let input3 = ['one'];
                              console.log("Result for input3:", arrayToCustomStr(input3));

                              // Fourth example, empty array.
                              let input4 = ;
                              console.log("Result for input4:", arrayToCustomStr(input4));

                              // Plus example.
                              let bob = [
                              "Don't worry about a thing",
                              "Cause every little thing",
                              "Gonna be all right",
                              "Saying, don't worry about a thing..."
                              ];
                              console.log("Result for bob:", arrayToCustomStr(bob));

                              .as-console-wrapper {
                              top: 0px;
                              max-height: 100% !important;
                              }





                              let arrayToCustomStr = (arr, enableMutate) =>
                              {
                              // Clone the received array (if required).
                              let a = enableMutate ? arr : arr.slice(0);

                              // Convert the array to custom string.
                              let removed = a.splice(-2, 2);
                              a.push(removed.join(" and "));
                              return a.join(", ");
                              }

                              // First example, mutate of original array is disabled.
                              let input1 = ['one', 'two', 'three', 'four'];
                              console.log("Result for input1:" , arrayToCustomStr(input1));
                              console.log("Original input1:", input1);

                              // Second example, mutate of original array is enabled.
                              let input2 = ['one', 'two'];
                              console.log("Result for input2:", arrayToCustomStr(input2, true));
                              console.log("Original input2:", input2);

                              // Third example, lenght of array is 1.
                              let input3 = ['one'];
                              console.log("Result for input3:", arrayToCustomStr(input3));

                              // Fourth example, empty array.
                              let input4 = ;
                              console.log("Result for input4:", arrayToCustomStr(input4));

                              // Plus example.
                              let bob = [
                              "Don't worry about a thing",
                              "Cause every little thing",
                              "Gonna be all right",
                              "Saying, don't worry about a thing..."
                              ];
                              console.log("Result for bob:", arrayToCustomStr(bob));

                              .as-console-wrapper {
                              top: 0px;
                              max-height: 100% !important;
                              }






                              share|improve this answer














                              share|improve this answer



                              share|improve this answer








                              edited Dec 23 '18 at 15:21

























                              answered Dec 21 '18 at 4:49









                              ShiderszShidersz

                              4,8042629




                              4,8042629























                                  1














                                  Using Array#reduce:



                                  ['one', 'two', 'three', 'four'].reduce(
                                  (a, b, i, array) => a + (i < array.length - 1 ? ', ' : ' and ') + b)






                                  share|improve this answer




























                                    1














                                    Using Array#reduce:



                                    ['one', 'two', 'three', 'four'].reduce(
                                    (a, b, i, array) => a + (i < array.length - 1 ? ', ' : ' and ') + b)






                                    share|improve this answer


























                                      1












                                      1








                                      1







                                      Using Array#reduce:



                                      ['one', 'two', 'three', 'four'].reduce(
                                      (a, b, i, array) => a + (i < array.length - 1 ? ', ' : ' and ') + b)






                                      share|improve this answer













                                      Using Array#reduce:



                                      ['one', 'two', 'three', 'four'].reduce(
                                      (a, b, i, array) => a + (i < array.length - 1 ? ', ' : ' and ') + b)







                                      share|improve this answer












                                      share|improve this answer



                                      share|improve this answer










                                      answered Dec 21 '18 at 16:27









                                      xqc winston mainxqc winston main

                                      111




                                      111






























                                          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.




                                          draft saved


                                          draft discarded














                                          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





















































                                          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

                                          Plaza Victoria

                                          Puebla de Zaragoza

                                          Musa