Join an array by commas and “and”












7














I want to convert the array ['one', 'two', 'three', 'four'] into one, two, three and four



Note that the first items have a comma, and but there is the word and between the second-last one and the last one.



The best solution I've come up with:



a.reduce( (res, v, i) => i === a.length - 2 ? res + v + ' and ' : res + v + ( i == a.length -1? '' : ', '), '' )


It's based on adding the commas at the end -- with the exception of the second-last one (a.length - 2) and with a way to avoid the last comma (a.length - 2).



SURELY there must be a better, neater, more intelligent way to do this?



It's a difficult topic to search on search engines because it contains the word "and"...










share|improve this question
























  • SURELY you value the serial/Oxford comma?!?
    – Argalatyr
    1 hour ago










  • You mean I should return one, two, three, and four?
    – Merc
    1 hour ago
















7














I want to convert the array ['one', 'two', 'three', 'four'] into one, two, three and four



Note that the first items have a comma, and but there is the word and between the second-last one and the last one.



The best solution I've come up with:



a.reduce( (res, v, i) => i === a.length - 2 ? res + v + ' and ' : res + v + ( i == a.length -1? '' : ', '), '' )


It's based on adding the commas at the end -- with the exception of the second-last one (a.length - 2) and with a way to avoid the last comma (a.length - 2).



SURELY there must be a better, neater, more intelligent way to do this?



It's a difficult topic to search on search engines because it contains the word "and"...










share|improve this question
























  • SURELY you value the serial/Oxford comma?!?
    – Argalatyr
    1 hour ago










  • You mean I should return one, two, three, and four?
    – Merc
    1 hour ago














7












7








7







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 39 mins ago









Bergi

362k57538861




362k57538861










asked 3 hours ago









Merc

6,77194785




6,77194785












  • SURELY you value the serial/Oxford comma?!?
    – Argalatyr
    1 hour ago










  • You mean I should return one, two, three, and four?
    – Merc
    1 hour ago


















  • SURELY you value the serial/Oxford comma?!?
    – Argalatyr
    1 hour ago










  • You mean I should return one, two, three, and four?
    – Merc
    1 hour ago
















SURELY you value the serial/Oxford comma?!?
– Argalatyr
1 hour ago




SURELY you value the serial/Oxford comma?!?
– Argalatyr
1 hour ago












You mean I should return one, two, three, and four?
– Merc
1 hour ago




You mean I should return one, two, three, and four?
– Merc
1 hour ago












4 Answers
4






active

oldest

votes


















10














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
    3 hours ago






  • 1




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










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






  • 2




    Very nice, thought the lack of the Oxford comma is killing me.
    – Mark Meyer
    2 hours ago










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



















3














I like Mark Meyer's approach (and would upvote if I had the rep) as it doesn't alter the input. Here's my spin:






function makeCommaSeparatedString(arr, useOxfordComma) {
const listStart = arr.slice(0, -1).join(', ');
const listEnd = arr.slice(-1);
const conjunction = arr.length <= 1 ? '' :
useOxfordComma && arr.length > 2 ? ', and ' : ' and ';

return [listStart, listEnd].join(conjunction);
}

console.log(makeCommaSeparatedString(['one', 'two', 'three', 'four']));
// one, two, three and four
console.log(makeCommaSeparatedString(['one', 'two', 'three', 'four'], true));
// one, two, three, and four
console.log(makeCommaSeparatedString(['one', 'two'], true));
// one and two
console.log(makeCommaSeparatedString(['one']));
// one
console.log(makeCommaSeparatedString());
//








share|improve this answer








New contributor




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


























    3














    You can use Array.prototype.slice()



    Code:






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

    const getResultString = arr => {
    if (!arr) return 'Provide a valid array..';
    const obj = { 0: '', 1: arr.toString() };
    return arr.length > 1
    ? `${arr.slice(0, -1).join(', ')} and ${arr.slice(-1)}`
    : obj[arr.length];
    }

    console.log(getResultString(input1));
    console.log(getResultString(input2));
    console.log(getResultString(input3));
    console.log(getResultString(input4));
    console.log(getResultString(null));








    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
      3 hours ago












    • @user2864740 Good comment, thanks
      – Yosvel Quintero
      3 hours ago






    • 1




      @user2864740 I have updated my answer for that type of input data..
      – Yosvel Quintero
      2 hours ago






    • 1




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










    • You are right @Merc, I have added validation..
      – Yosvel Quintero
      49 mins ago



















    2














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






    let input = ['one', 'two', 'three', 'four'];
    let removed = input.splice(-2, 2);
    input.push(removed.join(" and "));

    console.log(input.join(", "));








    share|improve this answer























      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53879088%2fjoin-an-array-by-commas-and-and%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      4 Answers
      4






      active

      oldest

      votes








      4 Answers
      4






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      10














      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
        3 hours ago






      • 1




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










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






      • 2




        Very nice, thought the lack of the Oxford comma is killing me.
        – Mark Meyer
        2 hours ago










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
















      10














      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
        3 hours ago






      • 1




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










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






      • 2




        Very nice, thought the lack of the Oxford comma is killing me.
        – Mark Meyer
        2 hours ago










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














      10












      10








      10






      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 1 hour ago

























      answered 3 hours ago









      CertainPerformance

      73.5k143455




      73.5k143455












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






      • 1




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










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






      • 2




        Very nice, thought the lack of the Oxford comma is killing me.
        – Mark Meyer
        2 hours ago










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


















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






      • 1




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










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






      • 2




        Very nice, thought the lack of the Oxford comma is killing me.
        – Mark Meyer
        2 hours ago










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
















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




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




      1




      1




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




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












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




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




      2




      2




      Very nice, thought the lack of the Oxford comma is killing me.
      – Mark Meyer
      2 hours ago




      Very nice, thought the lack of the Oxford comma is killing me.
      – Mark Meyer
      2 hours ago












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




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













      3














      I like Mark Meyer's approach (and would upvote if I had the rep) as it doesn't alter the input. Here's my spin:






      function makeCommaSeparatedString(arr, useOxfordComma) {
      const listStart = arr.slice(0, -1).join(', ');
      const listEnd = arr.slice(-1);
      const conjunction = arr.length <= 1 ? '' :
      useOxfordComma && arr.length > 2 ? ', and ' : ' and ';

      return [listStart, listEnd].join(conjunction);
      }

      console.log(makeCommaSeparatedString(['one', 'two', 'three', 'four']));
      // one, two, three and four
      console.log(makeCommaSeparatedString(['one', 'two', 'three', 'four'], true));
      // one, two, three, and four
      console.log(makeCommaSeparatedString(['one', 'two'], true));
      // one and two
      console.log(makeCommaSeparatedString(['one']));
      // one
      console.log(makeCommaSeparatedString());
      //








      share|improve this answer








      New contributor




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























        3














        I like Mark Meyer's approach (and would upvote if I had the rep) as it doesn't alter the input. Here's my spin:






        function makeCommaSeparatedString(arr, useOxfordComma) {
        const listStart = arr.slice(0, -1).join(', ');
        const listEnd = arr.slice(-1);
        const conjunction = arr.length <= 1 ? '' :
        useOxfordComma && arr.length > 2 ? ', and ' : ' and ';

        return [listStart, listEnd].join(conjunction);
        }

        console.log(makeCommaSeparatedString(['one', 'two', 'three', 'four']));
        // one, two, three and four
        console.log(makeCommaSeparatedString(['one', 'two', 'three', 'four'], true));
        // one, two, three, and four
        console.log(makeCommaSeparatedString(['one', 'two'], true));
        // one and two
        console.log(makeCommaSeparatedString(['one']));
        // one
        console.log(makeCommaSeparatedString());
        //








        share|improve this answer








        New contributor




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





















          3












          3








          3






          I like Mark Meyer's approach (and would upvote if I had the rep) as it doesn't alter the input. Here's my spin:






          function makeCommaSeparatedString(arr, useOxfordComma) {
          const listStart = arr.slice(0, -1).join(', ');
          const listEnd = arr.slice(-1);
          const conjunction = arr.length <= 1 ? '' :
          useOxfordComma && arr.length > 2 ? ', and ' : ' and ';

          return [listStart, listEnd].join(conjunction);
          }

          console.log(makeCommaSeparatedString(['one', 'two', 'three', 'four']));
          // one, two, three and four
          console.log(makeCommaSeparatedString(['one', 'two', 'three', 'four'], true));
          // one, two, three, and four
          console.log(makeCommaSeparatedString(['one', 'two'], true));
          // one and two
          console.log(makeCommaSeparatedString(['one']));
          // one
          console.log(makeCommaSeparatedString());
          //








          share|improve this answer








          New contributor




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









          I like Mark Meyer's approach (and would upvote if I had the rep) as it doesn't alter the input. Here's my spin:






          function makeCommaSeparatedString(arr, useOxfordComma) {
          const listStart = arr.slice(0, -1).join(', ');
          const listEnd = arr.slice(-1);
          const conjunction = arr.length <= 1 ? '' :
          useOxfordComma && arr.length > 2 ? ', and ' : ' and ';

          return [listStart, listEnd].join(conjunction);
          }

          console.log(makeCommaSeparatedString(['one', 'two', 'three', 'four']));
          // one, two, three and four
          console.log(makeCommaSeparatedString(['one', 'two', 'three', 'four'], true));
          // one, two, three, and four
          console.log(makeCommaSeparatedString(['one', 'two'], true));
          // one and two
          console.log(makeCommaSeparatedString(['one']));
          // one
          console.log(makeCommaSeparatedString());
          //








          function makeCommaSeparatedString(arr, useOxfordComma) {
          const listStart = arr.slice(0, -1).join(', ');
          const listEnd = arr.slice(-1);
          const conjunction = arr.length <= 1 ? '' :
          useOxfordComma && arr.length > 2 ? ', and ' : ' and ';

          return [listStart, listEnd].join(conjunction);
          }

          console.log(makeCommaSeparatedString(['one', 'two', 'three', 'four']));
          // one, two, three and four
          console.log(makeCommaSeparatedString(['one', 'two', 'three', 'four'], true));
          // one, two, three, and four
          console.log(makeCommaSeparatedString(['one', 'two'], true));
          // one and two
          console.log(makeCommaSeparatedString(['one']));
          // one
          console.log(makeCommaSeparatedString());
          //





          function makeCommaSeparatedString(arr, useOxfordComma) {
          const listStart = arr.slice(0, -1).join(', ');
          const listEnd = arr.slice(-1);
          const conjunction = arr.length <= 1 ? '' :
          useOxfordComma && arr.length > 2 ? ', and ' : ' and ';

          return [listStart, listEnd].join(conjunction);
          }

          console.log(makeCommaSeparatedString(['one', 'two', 'three', 'four']));
          // one, two, three and four
          console.log(makeCommaSeparatedString(['one', 'two', 'three', 'four'], true));
          // one, two, three, and four
          console.log(makeCommaSeparatedString(['one', 'two'], true));
          // one and two
          console.log(makeCommaSeparatedString(['one']));
          // one
          console.log(makeCommaSeparatedString());
          //






          share|improve this answer








          New contributor




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









          share|improve this answer



          share|improve this answer






          New contributor




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









          answered 2 hours ago









          Jug

          461




          461




          New contributor




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





          New contributor





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






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























              3














              You can use Array.prototype.slice()



              Code:






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

              const getResultString = arr => {
              if (!arr) return 'Provide a valid array..';
              const obj = { 0: '', 1: arr.toString() };
              return arr.length > 1
              ? `${arr.slice(0, -1).join(', ')} and ${arr.slice(-1)}`
              : obj[arr.length];
              }

              console.log(getResultString(input1));
              console.log(getResultString(input2));
              console.log(getResultString(input3));
              console.log(getResultString(input4));
              console.log(getResultString(null));








              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
                3 hours ago












              • @user2864740 Good comment, thanks
                – Yosvel Quintero
                3 hours ago






              • 1




                @user2864740 I have updated my answer for that type of input data..
                – Yosvel Quintero
                2 hours ago






              • 1




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










              • You are right @Merc, I have added validation..
                – Yosvel Quintero
                49 mins ago
















              3














              You can use Array.prototype.slice()



              Code:






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

              const getResultString = arr => {
              if (!arr) return 'Provide a valid array..';
              const obj = { 0: '', 1: arr.toString() };
              return arr.length > 1
              ? `${arr.slice(0, -1).join(', ')} and ${arr.slice(-1)}`
              : obj[arr.length];
              }

              console.log(getResultString(input1));
              console.log(getResultString(input2));
              console.log(getResultString(input3));
              console.log(getResultString(input4));
              console.log(getResultString(null));








              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
                3 hours ago












              • @user2864740 Good comment, thanks
                – Yosvel Quintero
                3 hours ago






              • 1




                @user2864740 I have updated my answer for that type of input data..
                – Yosvel Quintero
                2 hours ago






              • 1




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










              • You are right @Merc, I have added validation..
                – Yosvel Quintero
                49 mins ago














              3












              3








              3






              You can use Array.prototype.slice()



              Code:






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

              const getResultString = arr => {
              if (!arr) return 'Provide a valid array..';
              const obj = { 0: '', 1: arr.toString() };
              return arr.length > 1
              ? `${arr.slice(0, -1).join(', ')} and ${arr.slice(-1)}`
              : obj[arr.length];
              }

              console.log(getResultString(input1));
              console.log(getResultString(input2));
              console.log(getResultString(input3));
              console.log(getResultString(input4));
              console.log(getResultString(null));








              share|improve this answer














              You can use Array.prototype.slice()



              Code:






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

              const getResultString = arr => {
              if (!arr) return 'Provide a valid array..';
              const obj = { 0: '', 1: arr.toString() };
              return arr.length > 1
              ? `${arr.slice(0, -1).join(', ')} and ${arr.slice(-1)}`
              : obj[arr.length];
              }

              console.log(getResultString(input1));
              console.log(getResultString(input2));
              console.log(getResultString(input3));
              console.log(getResultString(input4));
              console.log(getResultString(null));








              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'];
              const input4 = ;

              const getResultString = arr => {
              if (!arr) return 'Provide a valid array..';
              const obj = { 0: '', 1: arr.toString() };
              return arr.length > 1
              ? `${arr.slice(0, -1).join(', ')} and ${arr.slice(-1)}`
              : obj[arr.length];
              }

              console.log(getResultString(input1));
              console.log(getResultString(input2));
              console.log(getResultString(input3));
              console.log(getResultString(input4));
              console.log(getResultString(null));





              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'];
              const input4 = ;

              const getResultString = arr => {
              if (!arr) return 'Provide a valid array..';
              const obj = { 0: '', 1: arr.toString() };
              return arr.length > 1
              ? `${arr.slice(0, -1).join(', ')} and ${arr.slice(-1)}`
              : obj[arr.length];
              }

              console.log(getResultString(input1));
              console.log(getResultString(input2));
              console.log(getResultString(input3));
              console.log(getResultString(input4));
              console.log(getResultString(null));






              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited 7 mins ago

























              answered 3 hours ago









              Yosvel Quintero

              10.9k42229




              10.9k42229








              • 1




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












              • @user2864740 Good comment, thanks
                – Yosvel Quintero
                3 hours ago






              • 1




                @user2864740 I have updated my answer for that type of input data..
                – Yosvel Quintero
                2 hours ago






              • 1




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










              • You are right @Merc, I have added validation..
                – Yosvel Quintero
                49 mins ago














              • 1




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












              • @user2864740 Good comment, thanks
                – Yosvel Quintero
                3 hours ago






              • 1




                @user2864740 I have updated my answer for that type of input data..
                – Yosvel Quintero
                2 hours ago






              • 1




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










              • You are right @Merc, I have added validation..
                – Yosvel Quintero
                49 mins ago








              1




              1




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






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














              @user2864740 Good comment, thanks
              – Yosvel Quintero
              3 hours ago




              @user2864740 Good comment, thanks
              – Yosvel Quintero
              3 hours ago




              1




              1




              @user2864740 I have updated my answer for that type of input data..
              – Yosvel Quintero
              2 hours ago




              @user2864740 I have updated my answer for that type of input data..
              – Yosvel Quintero
              2 hours ago




              1




              1




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




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












              You are right @Merc, I have added validation..
              – Yosvel Quintero
              49 mins ago




              You are right @Merc, I have added validation..
              – Yosvel Quintero
              49 mins ago











              2














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






              let input = ['one', 'two', 'three', 'four'];
              let removed = input.splice(-2, 2);
              input.push(removed.join(" and "));

              console.log(input.join(", "));








              share|improve this answer




























                2














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






                let input = ['one', 'two', 'three', 'four'];
                let removed = input.splice(-2, 2);
                input.push(removed.join(" and "));

                console.log(input.join(", "));








                share|improve this answer


























                  2












                  2








                  2






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






                  let input = ['one', 'two', 'three', 'four'];
                  let removed = input.splice(-2, 2);
                  input.push(removed.join(" and "));

                  console.log(input.join(", "));








                  share|improve this answer














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






                  let input = ['one', 'two', 'three', 'four'];
                  let removed = input.splice(-2, 2);
                  input.push(removed.join(" and "));

                  console.log(input.join(", "));








                  let input = ['one', 'two', 'three', 'four'];
                  let removed = input.splice(-2, 2);
                  input.push(removed.join(" and "));

                  console.log(input.join(", "));





                  let input = ['one', 'two', 'three', 'four'];
                  let removed = input.splice(-2, 2);
                  input.push(removed.join(" and "));

                  console.log(input.join(", "));






                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited 2 hours ago

























                  answered 2 hours ago









                  Shidersz

                  3,3161425




                  3,3161425






























                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.





                      Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                      Please pay close attention to the following guidance:


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53879088%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

                      Accessing regular linux commands in Huawei's Dopra Linux

                      Can't connect RFCOMM socket: Host is down

                      Kernel panic - not syncing: Fatal Exception in Interrupt