Array Stutter ImplementationPrinting a 2D arrayTesting if numbers in the array can be added up to equal the largest number in the arrayAnagram counterAccess an associative array value given an array of keys in PHPJavascript node/react web developer interview codeFilter array elements using variable number of filtersBit array implementationCount duplicates in a JavaScript arrayModify array of arrays to create custom array of objectsTwo-sum solution in JavaScript

What is the 中 in ダウンロード中?

Python program to convert a 24 hour format to 12 hour format

What are the benefits of cryosleep?

In general, would I need to season a meat when making a sauce?

Rests in pickup measure (anacrusis)

When and what was the first 3D acceleration device ever released?

Seed ship, unsexed person, cover has golden person attached to ship by umbilical cord

When do characters level up?

Logarithm of dependent variable is uniformly distributed. How to calculate a confidence interval for the mean?

ESTA/WVP - leaving US within 90 days, then staying in DR

How do you say “buy” in the sense of “believe”?

What is the difference between nullifying your vote and not going to vote at all?

Does revoking a certificate result in revocation of its key?

Canon 70D often overexposing or underexposing shots

Why colon to denote that a value belongs to a type?

Employer demanding to see degree after poor code review

Why do they consider the Ori false gods?

I unknowingly submitted plagiarised work

Is it ok to put a subplot to a story that is never meant to contribute to the development of the main plot?

Array Stutter Implementation

Is there a public standard for 8 and 10 character grid locators?

Source for parable about two fetuses

I think I may have violated academic integrity last year - what should I do?

How bitcoin nodes update UTXO set when their latests blocks are replaced?



Array Stutter Implementation


Printing a 2D arrayTesting if numbers in the array can be added up to equal the largest number in the arrayAnagram counterAccess an associative array value given an array of keys in PHPJavascript node/react web developer interview codeFilter array elements using variable number of filtersBit array implementationCount duplicates in a JavaScript arrayModify array of arrays to create custom array of objectsTwo-sum solution in JavaScript






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








1












$begingroup$


I was assigned this homework assignment to complete. The question originates from CodeStepByStep. Below is the prompt for the question:




Write a function stutter that takes an array of Strings as a parameter
and that replaces every String with two of that String. For example,
if an array stores the values ["how", "are", "you?"] before the
function is called, it should store the values ["how", "how", "are",
"are", "you?", "you?"] after the function finishes executing.




Below is my implementation:



function stutter(arr) 
if(arr.length == 0) return [];
if(arr.length == 1)
arr.push(arr[0]);
return arr;

let size = arr.length;
for(let i = 0; i < size + 2; i += 2)
arr.splice(i + 1, 0, arr[i]);

//If last two elements are not the same
if(arr[arr.length - 2] != arr[arr.length - 1] && arr.length != 1)
arr.push(arr[arr.length - 1]);

return arr;



It would be really helpful if I could get some feedback on how my code is written. I am fairly new to JavaScript, and I don't know some of the functions that could have made this a lot easier. Feedback on code efficiency and the implementation itself is warmly invited!










share|improve this question









$endgroup$


















    1












    $begingroup$


    I was assigned this homework assignment to complete. The question originates from CodeStepByStep. Below is the prompt for the question:




    Write a function stutter that takes an array of Strings as a parameter
    and that replaces every String with two of that String. For example,
    if an array stores the values ["how", "are", "you?"] before the
    function is called, it should store the values ["how", "how", "are",
    "are", "you?", "you?"] after the function finishes executing.




    Below is my implementation:



    function stutter(arr) 
    if(arr.length == 0) return [];
    if(arr.length == 1)
    arr.push(arr[0]);
    return arr;

    let size = arr.length;
    for(let i = 0; i < size + 2; i += 2)
    arr.splice(i + 1, 0, arr[i]);

    //If last two elements are not the same
    if(arr[arr.length - 2] != arr[arr.length - 1] && arr.length != 1)
    arr.push(arr[arr.length - 1]);

    return arr;



    It would be really helpful if I could get some feedback on how my code is written. I am fairly new to JavaScript, and I don't know some of the functions that could have made this a lot easier. Feedback on code efficiency and the implementation itself is warmly invited!










    share|improve this question









    $endgroup$














      1












      1








      1





      $begingroup$


      I was assigned this homework assignment to complete. The question originates from CodeStepByStep. Below is the prompt for the question:




      Write a function stutter that takes an array of Strings as a parameter
      and that replaces every String with two of that String. For example,
      if an array stores the values ["how", "are", "you?"] before the
      function is called, it should store the values ["how", "how", "are",
      "are", "you?", "you?"] after the function finishes executing.




      Below is my implementation:



      function stutter(arr) 
      if(arr.length == 0) return [];
      if(arr.length == 1)
      arr.push(arr[0]);
      return arr;

      let size = arr.length;
      for(let i = 0; i < size + 2; i += 2)
      arr.splice(i + 1, 0, arr[i]);

      //If last two elements are not the same
      if(arr[arr.length - 2] != arr[arr.length - 1] && arr.length != 1)
      arr.push(arr[arr.length - 1]);

      return arr;



      It would be really helpful if I could get some feedback on how my code is written. I am fairly new to JavaScript, and I don't know some of the functions that could have made this a lot easier. Feedback on code efficiency and the implementation itself is warmly invited!










      share|improve this question









      $endgroup$




      I was assigned this homework assignment to complete. The question originates from CodeStepByStep. Below is the prompt for the question:




      Write a function stutter that takes an array of Strings as a parameter
      and that replaces every String with two of that String. For example,
      if an array stores the values ["how", "are", "you?"] before the
      function is called, it should store the values ["how", "how", "are",
      "are", "you?", "you?"] after the function finishes executing.




      Below is my implementation:



      function stutter(arr) 
      if(arr.length == 0) return [];
      if(arr.length == 1)
      arr.push(arr[0]);
      return arr;

      let size = arr.length;
      for(let i = 0; i < size + 2; i += 2)
      arr.splice(i + 1, 0, arr[i]);

      //If last two elements are not the same
      if(arr[arr.length - 2] != arr[arr.length - 1] && arr.length != 1)
      arr.push(arr[arr.length - 1]);

      return arr;



      It would be really helpful if I could get some feedback on how my code is written. I am fairly new to JavaScript, and I don't know some of the functions that could have made this a lot easier. Feedback on code efficiency and the implementation itself is warmly invited!







      javascript array homework






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked 8 hours ago









      David WhiteDavid White

      779622




      779622




















          1 Answer
          1






          active

          oldest

          votes


















          5












          $begingroup$

          By reviewing your code, the first thing that comes to my mind is a lot of if statements. You should try and keep those minimal by writing solutions to be as general as they can be.



          Another thing that I don't like in your code is that you are doing manipulation of array passed to the function, instead of going out with a fresh one. It looks like this manipulation is what leads to a lot of ifs in the first place.



          So main point on how you can refactor your code is that you initialize an empty array which will act as a result and then manipulate that code:



          function stutter(arr) 
          const result = []

          for (let word of arr) // for..of loop is a bit clearer to read
          result.push(word, word) // push can accept N arguments


          return result



          So by initalizing resulting array with an empty one, you cleared of a case that the argument array passed in is empty, because for..of loop won't do the looping at all.
          I've used for..of loop here since it's less code, but you could also use the C-like for like you've written in your question. Note that that loop also wouldn't loop if the argument array was empty, therefor no need for the if(arr.length == 0).



          By the way, I'm a bit puzzled with what exactly is the point of the last if you have in the code, but I think that with the refactoring I've provided, then there is no need for it at all.




          Since you've asked for more JS way of doing this, here are two ways:



          Using map and flat (this one won't run in Edge):



          function stutter(arr) 
          return arr.map(x => [x, x]).flat()



          Using just reduce:



          function stutter(arr) 
          return arr.reduce((result, current) => [...result, current, current], [])






          share|improve this answer










          New contributor



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





          $endgroup$












          • $begingroup$
            Great answer and welcome to CR! There's also [].concat(...arr.map(e => [e, e])).
            $endgroup$
            – ggorlen
            49 mins ago











          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: "196"
          ;
          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: false,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: null,
          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%2fcodereview.stackexchange.com%2fquestions%2f221064%2farray-stutter-implementation%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          5












          $begingroup$

          By reviewing your code, the first thing that comes to my mind is a lot of if statements. You should try and keep those minimal by writing solutions to be as general as they can be.



          Another thing that I don't like in your code is that you are doing manipulation of array passed to the function, instead of going out with a fresh one. It looks like this manipulation is what leads to a lot of ifs in the first place.



          So main point on how you can refactor your code is that you initialize an empty array which will act as a result and then manipulate that code:



          function stutter(arr) 
          const result = []

          for (let word of arr) // for..of loop is a bit clearer to read
          result.push(word, word) // push can accept N arguments


          return result



          So by initalizing resulting array with an empty one, you cleared of a case that the argument array passed in is empty, because for..of loop won't do the looping at all.
          I've used for..of loop here since it's less code, but you could also use the C-like for like you've written in your question. Note that that loop also wouldn't loop if the argument array was empty, therefor no need for the if(arr.length == 0).



          By the way, I'm a bit puzzled with what exactly is the point of the last if you have in the code, but I think that with the refactoring I've provided, then there is no need for it at all.




          Since you've asked for more JS way of doing this, here are two ways:



          Using map and flat (this one won't run in Edge):



          function stutter(arr) 
          return arr.map(x => [x, x]).flat()



          Using just reduce:



          function stutter(arr) 
          return arr.reduce((result, current) => [...result, current, current], [])






          share|improve this answer










          New contributor



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





          $endgroup$












          • $begingroup$
            Great answer and welcome to CR! There's also [].concat(...arr.map(e => [e, e])).
            $endgroup$
            – ggorlen
            49 mins ago















          5












          $begingroup$

          By reviewing your code, the first thing that comes to my mind is a lot of if statements. You should try and keep those minimal by writing solutions to be as general as they can be.



          Another thing that I don't like in your code is that you are doing manipulation of array passed to the function, instead of going out with a fresh one. It looks like this manipulation is what leads to a lot of ifs in the first place.



          So main point on how you can refactor your code is that you initialize an empty array which will act as a result and then manipulate that code:



          function stutter(arr) 
          const result = []

          for (let word of arr) // for..of loop is a bit clearer to read
          result.push(word, word) // push can accept N arguments


          return result



          So by initalizing resulting array with an empty one, you cleared of a case that the argument array passed in is empty, because for..of loop won't do the looping at all.
          I've used for..of loop here since it's less code, but you could also use the C-like for like you've written in your question. Note that that loop also wouldn't loop if the argument array was empty, therefor no need for the if(arr.length == 0).



          By the way, I'm a bit puzzled with what exactly is the point of the last if you have in the code, but I think that with the refactoring I've provided, then there is no need for it at all.




          Since you've asked for more JS way of doing this, here are two ways:



          Using map and flat (this one won't run in Edge):



          function stutter(arr) 
          return arr.map(x => [x, x]).flat()



          Using just reduce:



          function stutter(arr) 
          return arr.reduce((result, current) => [...result, current, current], [])






          share|improve this answer










          New contributor



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





          $endgroup$












          • $begingroup$
            Great answer and welcome to CR! There's also [].concat(...arr.map(e => [e, e])).
            $endgroup$
            – ggorlen
            49 mins ago













          5












          5








          5





          $begingroup$

          By reviewing your code, the first thing that comes to my mind is a lot of if statements. You should try and keep those minimal by writing solutions to be as general as they can be.



          Another thing that I don't like in your code is that you are doing manipulation of array passed to the function, instead of going out with a fresh one. It looks like this manipulation is what leads to a lot of ifs in the first place.



          So main point on how you can refactor your code is that you initialize an empty array which will act as a result and then manipulate that code:



          function stutter(arr) 
          const result = []

          for (let word of arr) // for..of loop is a bit clearer to read
          result.push(word, word) // push can accept N arguments


          return result



          So by initalizing resulting array with an empty one, you cleared of a case that the argument array passed in is empty, because for..of loop won't do the looping at all.
          I've used for..of loop here since it's less code, but you could also use the C-like for like you've written in your question. Note that that loop also wouldn't loop if the argument array was empty, therefor no need for the if(arr.length == 0).



          By the way, I'm a bit puzzled with what exactly is the point of the last if you have in the code, but I think that with the refactoring I've provided, then there is no need for it at all.




          Since you've asked for more JS way of doing this, here are two ways:



          Using map and flat (this one won't run in Edge):



          function stutter(arr) 
          return arr.map(x => [x, x]).flat()



          Using just reduce:



          function stutter(arr) 
          return arr.reduce((result, current) => [...result, current, current], [])






          share|improve this answer










          New contributor



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





          $endgroup$



          By reviewing your code, the first thing that comes to my mind is a lot of if statements. You should try and keep those minimal by writing solutions to be as general as they can be.



          Another thing that I don't like in your code is that you are doing manipulation of array passed to the function, instead of going out with a fresh one. It looks like this manipulation is what leads to a lot of ifs in the first place.



          So main point on how you can refactor your code is that you initialize an empty array which will act as a result and then manipulate that code:



          function stutter(arr) 
          const result = []

          for (let word of arr) // for..of loop is a bit clearer to read
          result.push(word, word) // push can accept N arguments


          return result



          So by initalizing resulting array with an empty one, you cleared of a case that the argument array passed in is empty, because for..of loop won't do the looping at all.
          I've used for..of loop here since it's less code, but you could also use the C-like for like you've written in your question. Note that that loop also wouldn't loop if the argument array was empty, therefor no need for the if(arr.length == 0).



          By the way, I'm a bit puzzled with what exactly is the point of the last if you have in the code, but I think that with the refactoring I've provided, then there is no need for it at all.




          Since you've asked for more JS way of doing this, here are two ways:



          Using map and flat (this one won't run in Edge):



          function stutter(arr) 
          return arr.map(x => [x, x]).flat()



          Using just reduce:



          function stutter(arr) 
          return arr.reduce((result, current) => [...result, current, current], [])







          share|improve this answer










          New contributor



          Pritilender 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








          edited 4 hours ago









          AlexV

          2,273824




          2,273824






          New contributor



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








          answered 6 hours ago









          PritilenderPritilender

          512




          512




          New contributor



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




          New contributor




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













          • $begingroup$
            Great answer and welcome to CR! There's also [].concat(...arr.map(e => [e, e])).
            $endgroup$
            – ggorlen
            49 mins ago
















          • $begingroup$
            Great answer and welcome to CR! There's also [].concat(...arr.map(e => [e, e])).
            $endgroup$
            – ggorlen
            49 mins ago















          $begingroup$
          Great answer and welcome to CR! There's also [].concat(...arr.map(e => [e, e])).
          $endgroup$
          – ggorlen
          49 mins ago




          $begingroup$
          Great answer and welcome to CR! There's also [].concat(...arr.map(e => [e, e])).
          $endgroup$
          – ggorlen
          49 mins ago

















          draft saved

          draft discarded
















































          Thanks for contributing an answer to Code Review Stack Exchange!


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

          Use MathJax to format equations. MathJax reference.


          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%2fcodereview.stackexchange.com%2fquestions%2f221064%2farray-stutter-implementation%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

          Canceling a color specificationRandomly assigning color to Graphics3D objects?Default color for Filling in Mathematica 9Coloring specific elements of sets with a prime modified order in an array plotHow to pick a color differing significantly from the colors already in a given color list?Detection of the text colorColor numbers based on their valueCan color schemes for use with ColorData include opacity specification?My dynamic color schemes

          Invision Community Contents History See also References External links Navigation menuProprietaryinvisioncommunity.comIPS Community ForumsIPS Community Forumsthis blog entry"License Changes, IP.Board 3.4, and the Future""Interview -- Matt Mecham of Ibforums""CEO Invision Power Board, Matt Mecham Is a Liar, Thief!"IPB License Explanation 1.3, 1.3.1, 2.0, and 2.1ArchivedSecurity Fixes, Updates And Enhancements For IPB 1.3.1Archived"New Demo Accounts - Invision Power Services"the original"New Default Skin"the original"Invision Power Board 3.0.0 and Applications Released"the original"Archived copy"the original"Perpetual licenses being done away with""Release Notes - Invision Power Services""Introducing: IPS Community Suite 4!"Invision Community Release Notes

          François Viète Contents Biography Work and thought Bibliography See also Notes Further reading External links Navigation menup. 21Google Bookspp. 75–77Google BooksDe thou (from University of Saint Andrews)ArchivedGoogle BooksGoogle BooksGoogle BooksGoogle booksGoogle Bookscc-parthenay.frL'histoire universelle (fr)Universal History (en)ArchivedAdsabs.harvard.eduPagesperso-orange.frArchive.orgChikara Sasaki. Descartes' mathematical thought p.259Google BooksGoogle BooksGoogle Bookspp. 152 and onwardGoogle BooksGoogle BooksScribd.comGoogle Books1257-7979Google BooksGoogle BooksGoogle BooksGoogle BooksGoogle BooksGoogle BooksGallica.bnf.frGoogle BooksGoogle Books"François Viète"Francois Viète: Father of Modern Algebraic NotationThe Lawyer and the GamblerAbout TarporleySite de Jean-Paul GuichardL'algèbre nouvelle"About the Harmonicon"cb120511976(data)1188044800000 0001 0913 5903n82164680ola2013766880073431702w6vt1sb70287374827140948071409480