refactoring a function using reduce - javascript












2















I've written a function to turn a string such as 'aaazeeeee' into a new string of 'aaa z eeeee'



this is the code I've tried that works






const groupCharacters = signature => {
let newSignature = "", arr = ;

let result = [...signature].reduce((accumulator, element, index) => {
// check if last element in accumulator matches current element
if (accumulator[accumulator.length -1] !== element) {
// push accumulator into array
arr.push(accumulator);
// set newSignature as new element
newSignature = element;
} else {
// else add element to newSignature
newSignature = accumulator += element;
}

// if is last item, push to array
if (index === signature.length - 1) arr.push(element);

return newSignature;
})

return arr;
}

console.log(groupCharacters('aabaaaaa'));





how can I refactor it so that I don't need the new string or array? I've tried something like this






const groupCharacters = str => [...str].reduce((accumulator, element) => accumulator[accumulator.length - 1] !== element ? `${accumulator} ` : accumulator + element)





it outputs 'aaa '



how do I fix it or use something like map instead?










share|improve this question





























    2















    I've written a function to turn a string such as 'aaazeeeee' into a new string of 'aaa z eeeee'



    this is the code I've tried that works






    const groupCharacters = signature => {
    let newSignature = "", arr = ;

    let result = [...signature].reduce((accumulator, element, index) => {
    // check if last element in accumulator matches current element
    if (accumulator[accumulator.length -1] !== element) {
    // push accumulator into array
    arr.push(accumulator);
    // set newSignature as new element
    newSignature = element;
    } else {
    // else add element to newSignature
    newSignature = accumulator += element;
    }

    // if is last item, push to array
    if (index === signature.length - 1) arr.push(element);

    return newSignature;
    })

    return arr;
    }

    console.log(groupCharacters('aabaaaaa'));





    how can I refactor it so that I don't need the new string or array? I've tried something like this






    const groupCharacters = str => [...str].reduce((accumulator, element) => accumulator[accumulator.length - 1] !== element ? `${accumulator} ` : accumulator + element)





    it outputs 'aaa '



    how do I fix it or use something like map instead?










    share|improve this question



























      2












      2








      2








      I've written a function to turn a string such as 'aaazeeeee' into a new string of 'aaa z eeeee'



      this is the code I've tried that works






      const groupCharacters = signature => {
      let newSignature = "", arr = ;

      let result = [...signature].reduce((accumulator, element, index) => {
      // check if last element in accumulator matches current element
      if (accumulator[accumulator.length -1] !== element) {
      // push accumulator into array
      arr.push(accumulator);
      // set newSignature as new element
      newSignature = element;
      } else {
      // else add element to newSignature
      newSignature = accumulator += element;
      }

      // if is last item, push to array
      if (index === signature.length - 1) arr.push(element);

      return newSignature;
      })

      return arr;
      }

      console.log(groupCharacters('aabaaaaa'));





      how can I refactor it so that I don't need the new string or array? I've tried something like this






      const groupCharacters = str => [...str].reduce((accumulator, element) => accumulator[accumulator.length - 1] !== element ? `${accumulator} ` : accumulator + element)





      it outputs 'aaa '



      how do I fix it or use something like map instead?










      share|improve this question
















      I've written a function to turn a string such as 'aaazeeeee' into a new string of 'aaa z eeeee'



      this is the code I've tried that works






      const groupCharacters = signature => {
      let newSignature = "", arr = ;

      let result = [...signature].reduce((accumulator, element, index) => {
      // check if last element in accumulator matches current element
      if (accumulator[accumulator.length -1] !== element) {
      // push accumulator into array
      arr.push(accumulator);
      // set newSignature as new element
      newSignature = element;
      } else {
      // else add element to newSignature
      newSignature = accumulator += element;
      }

      // if is last item, push to array
      if (index === signature.length - 1) arr.push(element);

      return newSignature;
      })

      return arr;
      }

      console.log(groupCharacters('aabaaaaa'));





      how can I refactor it so that I don't need the new string or array? I've tried something like this






      const groupCharacters = str => [...str].reduce((accumulator, element) => accumulator[accumulator.length - 1] !== element ? `${accumulator} ` : accumulator + element)





      it outputs 'aaa '



      how do I fix it or use something like map instead?






      const groupCharacters = signature => {
      let newSignature = "", arr = ;

      let result = [...signature].reduce((accumulator, element, index) => {
      // check if last element in accumulator matches current element
      if (accumulator[accumulator.length -1] !== element) {
      // push accumulator into array
      arr.push(accumulator);
      // set newSignature as new element
      newSignature = element;
      } else {
      // else add element to newSignature
      newSignature = accumulator += element;
      }

      // if is last item, push to array
      if (index === signature.length - 1) arr.push(element);

      return newSignature;
      })

      return arr;
      }

      console.log(groupCharacters('aabaaaaa'));





      const groupCharacters = signature => {
      let newSignature = "", arr = ;

      let result = [...signature].reduce((accumulator, element, index) => {
      // check if last element in accumulator matches current element
      if (accumulator[accumulator.length -1] !== element) {
      // push accumulator into array
      arr.push(accumulator);
      // set newSignature as new element
      newSignature = element;
      } else {
      // else add element to newSignature
      newSignature = accumulator += element;
      }

      // if is last item, push to array
      if (index === signature.length - 1) arr.push(element);

      return newSignature;
      })

      return arr;
      }

      console.log(groupCharacters('aabaaaaa'));





      const groupCharacters = str => [...str].reduce((accumulator, element) => accumulator[accumulator.length - 1] !== element ? `${accumulator} ` : accumulator + element)





      const groupCharacters = str => [...str].reduce((accumulator, element) => accumulator[accumulator.length - 1] !== element ? `${accumulator} ` : accumulator + element)






      javascript






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 13 '18 at 5:55









      CertainPerformance

      82.1k144067




      82.1k144067










      asked Nov 13 '18 at 5:47









      totalnoobtotalnoob

      3261631




      3261631
























          2 Answers
          2






          active

          oldest

          votes


















          5














          To change your existing code but still use reduce, I'd suggest reduceing into a string, rather than array: on each iteration, concatenate with the current character, and also concatenate with a space if the next character is both defined and is not equal to the current character:






          const groupCharacters = str => (
          [...str].reduce((a, char, i) => a + char + (
          str[i + 1] === char || str[i + 1] === undefined
          ? ''
          : ' '
          ), '')
          );

          console.log(groupCharacters('aaazeeeee'));





          Or, you could use a simple regular expression - capture a word character in a group, then backreference that group as many times as possible, and replace with the whole match plus a space:






          const groupCharacters = signature => signature.replace(/(w)1*(?!1|$)/g, '$& ');
          console.log(groupCharacters('aaazeeeee'));





          To break it down:




          • (w) - Match any word character, capture it in the first group (so it can be backreferenced later using 1)


          • 1* - Greedily repeat the character that was just matched zero or more times (repeat as much as possible)


          • (?!1|$) - Checks that the substring that was just matched is not followed by either the end of the string, or by another of the same character. This ensures that the final repeated substring doesn't get a space appended to it as well (that is, you don't want 'aaa z eeeee ').



          As a side note, the regex G(w)1*+(?!$) would accomplish the same thing, is nicer to read, and is notably more efficient (the G matches the end of the last match or the beginning of the string, and the + in 1*+ makes the repetition possessive, which means that, on the final substring, the engine will be unable to backtrack, and thus fail immediately once the final full substring is checked, rather than iterating through each of its characters first). But, unfortunately, native JS doesn't support possessive quantifiers, nor the G anchor.






          share|improve this answer


























          • This looks amazing! Can you please explain in simpler words how does it work?

            – vibhor1997a
            Nov 13 '18 at 5:55











          • that's pretty cool, but I'd like to see how the reduce method can be refactored

            – totalnoob
            Nov 13 '18 at 6:11











          • @totalnoob See edit, reduce into a string instead of to an array

            – CertainPerformance
            Nov 13 '18 at 6:27











          • the result of the reduce version has an extra space at the end of it

            – totalnoob
            Nov 13 '18 at 6:44













          • what's the performance of these like in complexity?

            – totalnoob
            Nov 13 '18 at 17:03



















          1














          I would do this using reduce with something like this as the OP wants to do with reduce:-






          function myFunc(str) {
          return str.split('').reduce(function (acc, cv, ci) {
          if (acc.lastElem != cv) {
          acc.str += (acc.lastElem == "") ? cv : ' ' + cv;
          }
          else {
          acc.str += cv;
          }
          acc.lastElem = cv;
          return acc;
          }, { lastElem: '', str: '' }).str;
          }
          console.log(myFunc('aaabbbcc'));
          console.log(myFunc('aaazeeeee'))





          How it works?



          The accumulator is an object with keys lastElem(the previous element than the current element) and str(the string forming).






          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%2f53274580%2frefactoring-a-function-using-reduce-javascript%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            2 Answers
            2






            active

            oldest

            votes








            2 Answers
            2






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            5














            To change your existing code but still use reduce, I'd suggest reduceing into a string, rather than array: on each iteration, concatenate with the current character, and also concatenate with a space if the next character is both defined and is not equal to the current character:






            const groupCharacters = str => (
            [...str].reduce((a, char, i) => a + char + (
            str[i + 1] === char || str[i + 1] === undefined
            ? ''
            : ' '
            ), '')
            );

            console.log(groupCharacters('aaazeeeee'));





            Or, you could use a simple regular expression - capture a word character in a group, then backreference that group as many times as possible, and replace with the whole match plus a space:






            const groupCharacters = signature => signature.replace(/(w)1*(?!1|$)/g, '$& ');
            console.log(groupCharacters('aaazeeeee'));





            To break it down:




            • (w) - Match any word character, capture it in the first group (so it can be backreferenced later using 1)


            • 1* - Greedily repeat the character that was just matched zero or more times (repeat as much as possible)


            • (?!1|$) - Checks that the substring that was just matched is not followed by either the end of the string, or by another of the same character. This ensures that the final repeated substring doesn't get a space appended to it as well (that is, you don't want 'aaa z eeeee ').



            As a side note, the regex G(w)1*+(?!$) would accomplish the same thing, is nicer to read, and is notably more efficient (the G matches the end of the last match or the beginning of the string, and the + in 1*+ makes the repetition possessive, which means that, on the final substring, the engine will be unable to backtrack, and thus fail immediately once the final full substring is checked, rather than iterating through each of its characters first). But, unfortunately, native JS doesn't support possessive quantifiers, nor the G anchor.






            share|improve this answer


























            • This looks amazing! Can you please explain in simpler words how does it work?

              – vibhor1997a
              Nov 13 '18 at 5:55











            • that's pretty cool, but I'd like to see how the reduce method can be refactored

              – totalnoob
              Nov 13 '18 at 6:11











            • @totalnoob See edit, reduce into a string instead of to an array

              – CertainPerformance
              Nov 13 '18 at 6:27











            • the result of the reduce version has an extra space at the end of it

              – totalnoob
              Nov 13 '18 at 6:44













            • what's the performance of these like in complexity?

              – totalnoob
              Nov 13 '18 at 17:03
















            5














            To change your existing code but still use reduce, I'd suggest reduceing into a string, rather than array: on each iteration, concatenate with the current character, and also concatenate with a space if the next character is both defined and is not equal to the current character:






            const groupCharacters = str => (
            [...str].reduce((a, char, i) => a + char + (
            str[i + 1] === char || str[i + 1] === undefined
            ? ''
            : ' '
            ), '')
            );

            console.log(groupCharacters('aaazeeeee'));





            Or, you could use a simple regular expression - capture a word character in a group, then backreference that group as many times as possible, and replace with the whole match plus a space:






            const groupCharacters = signature => signature.replace(/(w)1*(?!1|$)/g, '$& ');
            console.log(groupCharacters('aaazeeeee'));





            To break it down:




            • (w) - Match any word character, capture it in the first group (so it can be backreferenced later using 1)


            • 1* - Greedily repeat the character that was just matched zero or more times (repeat as much as possible)


            • (?!1|$) - Checks that the substring that was just matched is not followed by either the end of the string, or by another of the same character. This ensures that the final repeated substring doesn't get a space appended to it as well (that is, you don't want 'aaa z eeeee ').



            As a side note, the regex G(w)1*+(?!$) would accomplish the same thing, is nicer to read, and is notably more efficient (the G matches the end of the last match or the beginning of the string, and the + in 1*+ makes the repetition possessive, which means that, on the final substring, the engine will be unable to backtrack, and thus fail immediately once the final full substring is checked, rather than iterating through each of its characters first). But, unfortunately, native JS doesn't support possessive quantifiers, nor the G anchor.






            share|improve this answer


























            • This looks amazing! Can you please explain in simpler words how does it work?

              – vibhor1997a
              Nov 13 '18 at 5:55











            • that's pretty cool, but I'd like to see how the reduce method can be refactored

              – totalnoob
              Nov 13 '18 at 6:11











            • @totalnoob See edit, reduce into a string instead of to an array

              – CertainPerformance
              Nov 13 '18 at 6:27











            • the result of the reduce version has an extra space at the end of it

              – totalnoob
              Nov 13 '18 at 6:44













            • what's the performance of these like in complexity?

              – totalnoob
              Nov 13 '18 at 17:03














            5












            5








            5







            To change your existing code but still use reduce, I'd suggest reduceing into a string, rather than array: on each iteration, concatenate with the current character, and also concatenate with a space if the next character is both defined and is not equal to the current character:






            const groupCharacters = str => (
            [...str].reduce((a, char, i) => a + char + (
            str[i + 1] === char || str[i + 1] === undefined
            ? ''
            : ' '
            ), '')
            );

            console.log(groupCharacters('aaazeeeee'));





            Or, you could use a simple regular expression - capture a word character in a group, then backreference that group as many times as possible, and replace with the whole match plus a space:






            const groupCharacters = signature => signature.replace(/(w)1*(?!1|$)/g, '$& ');
            console.log(groupCharacters('aaazeeeee'));





            To break it down:




            • (w) - Match any word character, capture it in the first group (so it can be backreferenced later using 1)


            • 1* - Greedily repeat the character that was just matched zero or more times (repeat as much as possible)


            • (?!1|$) - Checks that the substring that was just matched is not followed by either the end of the string, or by another of the same character. This ensures that the final repeated substring doesn't get a space appended to it as well (that is, you don't want 'aaa z eeeee ').



            As a side note, the regex G(w)1*+(?!$) would accomplish the same thing, is nicer to read, and is notably more efficient (the G matches the end of the last match or the beginning of the string, and the + in 1*+ makes the repetition possessive, which means that, on the final substring, the engine will be unable to backtrack, and thus fail immediately once the final full substring is checked, rather than iterating through each of its characters first). But, unfortunately, native JS doesn't support possessive quantifiers, nor the G anchor.






            share|improve this answer















            To change your existing code but still use reduce, I'd suggest reduceing into a string, rather than array: on each iteration, concatenate with the current character, and also concatenate with a space if the next character is both defined and is not equal to the current character:






            const groupCharacters = str => (
            [...str].reduce((a, char, i) => a + char + (
            str[i + 1] === char || str[i + 1] === undefined
            ? ''
            : ' '
            ), '')
            );

            console.log(groupCharacters('aaazeeeee'));





            Or, you could use a simple regular expression - capture a word character in a group, then backreference that group as many times as possible, and replace with the whole match plus a space:






            const groupCharacters = signature => signature.replace(/(w)1*(?!1|$)/g, '$& ');
            console.log(groupCharacters('aaazeeeee'));





            To break it down:




            • (w) - Match any word character, capture it in the first group (so it can be backreferenced later using 1)


            • 1* - Greedily repeat the character that was just matched zero or more times (repeat as much as possible)


            • (?!1|$) - Checks that the substring that was just matched is not followed by either the end of the string, or by another of the same character. This ensures that the final repeated substring doesn't get a space appended to it as well (that is, you don't want 'aaa z eeeee ').



            As a side note, the regex G(w)1*+(?!$) would accomplish the same thing, is nicer to read, and is notably more efficient (the G matches the end of the last match or the beginning of the string, and the + in 1*+ makes the repetition possessive, which means that, on the final substring, the engine will be unable to backtrack, and thus fail immediately once the final full substring is checked, rather than iterating through each of its characters first). But, unfortunately, native JS doesn't support possessive quantifiers, nor the G anchor.






            const groupCharacters = str => (
            [...str].reduce((a, char, i) => a + char + (
            str[i + 1] === char || str[i + 1] === undefined
            ? ''
            : ' '
            ), '')
            );

            console.log(groupCharacters('aaazeeeee'));





            const groupCharacters = str => (
            [...str].reduce((a, char, i) => a + char + (
            str[i + 1] === char || str[i + 1] === undefined
            ? ''
            : ' '
            ), '')
            );

            console.log(groupCharacters('aaazeeeee'));





            const groupCharacters = signature => signature.replace(/(w)1*(?!1|$)/g, '$& ');
            console.log(groupCharacters('aaazeeeee'));





            const groupCharacters = signature => signature.replace(/(w)1*(?!1|$)/g, '$& ');
            console.log(groupCharacters('aaazeeeee'));






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Nov 13 '18 at 6:45

























            answered Nov 13 '18 at 5:51









            CertainPerformanceCertainPerformance

            82.1k144067




            82.1k144067













            • This looks amazing! Can you please explain in simpler words how does it work?

              – vibhor1997a
              Nov 13 '18 at 5:55











            • that's pretty cool, but I'd like to see how the reduce method can be refactored

              – totalnoob
              Nov 13 '18 at 6:11











            • @totalnoob See edit, reduce into a string instead of to an array

              – CertainPerformance
              Nov 13 '18 at 6:27











            • the result of the reduce version has an extra space at the end of it

              – totalnoob
              Nov 13 '18 at 6:44













            • what's the performance of these like in complexity?

              – totalnoob
              Nov 13 '18 at 17:03



















            • This looks amazing! Can you please explain in simpler words how does it work?

              – vibhor1997a
              Nov 13 '18 at 5:55











            • that's pretty cool, but I'd like to see how the reduce method can be refactored

              – totalnoob
              Nov 13 '18 at 6:11











            • @totalnoob See edit, reduce into a string instead of to an array

              – CertainPerformance
              Nov 13 '18 at 6:27











            • the result of the reduce version has an extra space at the end of it

              – totalnoob
              Nov 13 '18 at 6:44













            • what's the performance of these like in complexity?

              – totalnoob
              Nov 13 '18 at 17:03

















            This looks amazing! Can you please explain in simpler words how does it work?

            – vibhor1997a
            Nov 13 '18 at 5:55





            This looks amazing! Can you please explain in simpler words how does it work?

            – vibhor1997a
            Nov 13 '18 at 5:55













            that's pretty cool, but I'd like to see how the reduce method can be refactored

            – totalnoob
            Nov 13 '18 at 6:11





            that's pretty cool, but I'd like to see how the reduce method can be refactored

            – totalnoob
            Nov 13 '18 at 6:11













            @totalnoob See edit, reduce into a string instead of to an array

            – CertainPerformance
            Nov 13 '18 at 6:27





            @totalnoob See edit, reduce into a string instead of to an array

            – CertainPerformance
            Nov 13 '18 at 6:27













            the result of the reduce version has an extra space at the end of it

            – totalnoob
            Nov 13 '18 at 6:44







            the result of the reduce version has an extra space at the end of it

            – totalnoob
            Nov 13 '18 at 6:44















            what's the performance of these like in complexity?

            – totalnoob
            Nov 13 '18 at 17:03





            what's the performance of these like in complexity?

            – totalnoob
            Nov 13 '18 at 17:03













            1














            I would do this using reduce with something like this as the OP wants to do with reduce:-






            function myFunc(str) {
            return str.split('').reduce(function (acc, cv, ci) {
            if (acc.lastElem != cv) {
            acc.str += (acc.lastElem == "") ? cv : ' ' + cv;
            }
            else {
            acc.str += cv;
            }
            acc.lastElem = cv;
            return acc;
            }, { lastElem: '', str: '' }).str;
            }
            console.log(myFunc('aaabbbcc'));
            console.log(myFunc('aaazeeeee'))





            How it works?



            The accumulator is an object with keys lastElem(the previous element than the current element) and str(the string forming).






            share|improve this answer




























              1














              I would do this using reduce with something like this as the OP wants to do with reduce:-






              function myFunc(str) {
              return str.split('').reduce(function (acc, cv, ci) {
              if (acc.lastElem != cv) {
              acc.str += (acc.lastElem == "") ? cv : ' ' + cv;
              }
              else {
              acc.str += cv;
              }
              acc.lastElem = cv;
              return acc;
              }, { lastElem: '', str: '' }).str;
              }
              console.log(myFunc('aaabbbcc'));
              console.log(myFunc('aaazeeeee'))





              How it works?



              The accumulator is an object with keys lastElem(the previous element than the current element) and str(the string forming).






              share|improve this answer


























                1












                1








                1







                I would do this using reduce with something like this as the OP wants to do with reduce:-






                function myFunc(str) {
                return str.split('').reduce(function (acc, cv, ci) {
                if (acc.lastElem != cv) {
                acc.str += (acc.lastElem == "") ? cv : ' ' + cv;
                }
                else {
                acc.str += cv;
                }
                acc.lastElem = cv;
                return acc;
                }, { lastElem: '', str: '' }).str;
                }
                console.log(myFunc('aaabbbcc'));
                console.log(myFunc('aaazeeeee'))





                How it works?



                The accumulator is an object with keys lastElem(the previous element than the current element) and str(the string forming).






                share|improve this answer













                I would do this using reduce with something like this as the OP wants to do with reduce:-






                function myFunc(str) {
                return str.split('').reduce(function (acc, cv, ci) {
                if (acc.lastElem != cv) {
                acc.str += (acc.lastElem == "") ? cv : ' ' + cv;
                }
                else {
                acc.str += cv;
                }
                acc.lastElem = cv;
                return acc;
                }, { lastElem: '', str: '' }).str;
                }
                console.log(myFunc('aaabbbcc'));
                console.log(myFunc('aaazeeeee'))





                How it works?



                The accumulator is an object with keys lastElem(the previous element than the current element) and str(the string forming).






                function myFunc(str) {
                return str.split('').reduce(function (acc, cv, ci) {
                if (acc.lastElem != cv) {
                acc.str += (acc.lastElem == "") ? cv : ' ' + cv;
                }
                else {
                acc.str += cv;
                }
                acc.lastElem = cv;
                return acc;
                }, { lastElem: '', str: '' }).str;
                }
                console.log(myFunc('aaabbbcc'));
                console.log(myFunc('aaazeeeee'))





                function myFunc(str) {
                return str.split('').reduce(function (acc, cv, ci) {
                if (acc.lastElem != cv) {
                acc.str += (acc.lastElem == "") ? cv : ' ' + cv;
                }
                else {
                acc.str += cv;
                }
                acc.lastElem = cv;
                return acc;
                }, { lastElem: '', str: '' }).str;
                }
                console.log(myFunc('aaabbbcc'));
                console.log(myFunc('aaazeeeee'))






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 13 '18 at 6:27









                vibhor1997avibhor1997a

                1,5701624




                1,5701624






























                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


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

                    But avoid



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

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


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




                    draft saved


                    draft discarded














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

                    Full-time equivalent

                    さくらももこ

                    13 indicted, 8 arrested in Calif. drug cartel investigation