Join an array by commas and “and” [duplicate]

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP












17















This question already has an answer here:



  • Array to Comma separated string and for last tag use the 'and' instead of comma in jquery

    4 answers



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















marked as duplicate by deceze arrays
Users with the  arrays badge can single-handedly close arrays questions as duplicates and reopen them as needed.

StackExchange.ready(function()
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function()
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function()
$hover.showInfoMessage('',
messageElement: $msg.clone().show(),
transient: false,
position: my: 'bottom left', at: 'top center', offsetTop: -7 ,
dismissable: false,
relativeToBody: true
);
,
function()
StackExchange.helpers.removeMessages();

);
);
);
Dec 21 '18 at 16:57


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new 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















This question already has an answer here:



  • Array to Comma separated string and for last tag use the 'and' instead of comma in jquery

    4 answers



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















marked as duplicate by deceze arrays
Users with the  arrays badge can single-handedly close arrays questions as duplicates and reopen them as needed.

StackExchange.ready(function()
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function()
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function()
$hover.showInfoMessage('',
messageElement: $msg.clone().show(),
transient: false,
position: my: 'bottom left', at: 'top center', offsetTop: -7 ,
dismissable: false,
relativeToBody: true
);
,
function()
StackExchange.helpers.removeMessages();

);
);
);
Dec 21 '18 at 16:57


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new 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






This question already has an answer here:



  • Array to Comma separated string and for last tag use the 'and' instead of comma in jquery

    4 answers



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
















This question already has an answer here:



  • Array to Comma separated string and for last tag use the 'and' instead of comma in jquery

    4 answers



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





This question already has an answer here:



  • Array to Comma separated string and for last tag use the 'and' instead of comma in jquery

    4 answers







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

364k58541866




364k58541866










asked Dec 21 '18 at 4:15









Merc

6,86494788




6,86494788




marked as duplicate by deceze arrays
Users with the  arrays badge can single-handedly close arrays questions as duplicates and reopen them as needed.

StackExchange.ready(function()
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function()
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function()
$hover.showInfoMessage('',
messageElement: $msg.clone().show(),
transient: false,
position: my: 'bottom left', at: 'top center', offsetTop: -7 ,
dismissable: false,
relativeToBody: true
);
,
function()
StackExchange.helpers.removeMessages();

);
);
);
Dec 21 '18 at 16:57


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.






marked as duplicate by deceze arrays
Users with the  arrays badge can single-handedly close arrays questions as duplicates and reopen them as needed.

StackExchange.ready(function()
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function()
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function()
$hover.showInfoMessage('',
messageElement: $msg.clone().show(),
transient: false,
position: my: 'bottom left', at: 'top center', offsetTop: -7 ,
dismissable: false,
relativeToBody: true
);
,
function()
StackExchange.helpers.removeMessages();

);
);
);
Dec 21 '18 at 16:57


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new 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












  • 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




























    7














    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



























          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









          CertainPerformance

          76.5k143862




          76.5k143862











          • 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









              Jug

              1362




              1362





















                  7














                  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














                    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












                      7








                      7






                      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 Candellier

                      28729




                      28729





















                          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 Quintero

                          11k42330




                          11k42330







                          • 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









                              Shidersz

                              3,7762528




                              3,7762528





















                                  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 main

                                      111




                                      111












                                          Popular posts from this blog

                                          How to check contact read email or not when send email to Individual?

                                          Bahrain

                                          Postfix configuration issue with fips on centos 7; mailgun relay