How to add same elements to javascript array n times











up vote
6
down vote

favorite












var fruits = ;
fruits.push("lemon", "lemon", "lemon", "lemon");


Instead of pushing same elements how can write it once like this:



fruits.push("lemon" * 4 times)









share|improve this question
























  • They're not the same elements. The first one has uppercase L, the others have lowercase l.
    – Barmar
    Aug 14 at 1:05










  • changed the typo
    – Deke
    Aug 14 at 1:08










  • Possible duplicate of Create an array with same element repeated multiple times
    – Akrion
    Oct 12 at 6:07















up vote
6
down vote

favorite












var fruits = ;
fruits.push("lemon", "lemon", "lemon", "lemon");


Instead of pushing same elements how can write it once like this:



fruits.push("lemon" * 4 times)









share|improve this question
























  • They're not the same elements. The first one has uppercase L, the others have lowercase l.
    – Barmar
    Aug 14 at 1:05










  • changed the typo
    – Deke
    Aug 14 at 1:08










  • Possible duplicate of Create an array with same element repeated multiple times
    – Akrion
    Oct 12 at 6:07













up vote
6
down vote

favorite









up vote
6
down vote

favorite











var fruits = ;
fruits.push("lemon", "lemon", "lemon", "lemon");


Instead of pushing same elements how can write it once like this:



fruits.push("lemon" * 4 times)









share|improve this question















var fruits = ;
fruits.push("lemon", "lemon", "lemon", "lemon");


Instead of pushing same elements how can write it once like this:



fruits.push("lemon" * 4 times)






javascript






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Aug 14 at 6:28

























asked Aug 13 at 23:55









Deke

1,25611121




1,25611121












  • They're not the same elements. The first one has uppercase L, the others have lowercase l.
    – Barmar
    Aug 14 at 1:05










  • changed the typo
    – Deke
    Aug 14 at 1:08










  • Possible duplicate of Create an array with same element repeated multiple times
    – Akrion
    Oct 12 at 6:07


















  • They're not the same elements. The first one has uppercase L, the others have lowercase l.
    – Barmar
    Aug 14 at 1:05










  • changed the typo
    – Deke
    Aug 14 at 1:08










  • Possible duplicate of Create an array with same element repeated multiple times
    – Akrion
    Oct 12 at 6:07
















They're not the same elements. The first one has uppercase L, the others have lowercase l.
– Barmar
Aug 14 at 1:05




They're not the same elements. The first one has uppercase L, the others have lowercase l.
– Barmar
Aug 14 at 1:05












changed the typo
– Deke
Aug 14 at 1:08




changed the typo
– Deke
Aug 14 at 1:08












Possible duplicate of Create an array with same element repeated multiple times
– Akrion
Oct 12 at 6:07




Possible duplicate of Create an array with same element repeated multiple times
– Akrion
Oct 12 at 6:07












2 Answers
2






active

oldest

votes

















up vote
15
down vote



accepted










For primitives, use .fill:






var fruits = new Array(4).fill('Lemon');
console.log(fruits);





For non-primitives, don't use fill, because then all elements in the array will reference the same object in memory, so mutations to one item in the array will affect every item in the array - instead, explicitly create the object on each iteration, which can be done with Array.from:






var fruits = Array.from(
{ length: 4 },
() => ({ Lemon: 'Lemon' })
);
console.log(fruits);








share|improve this answer




























    up vote
    3
    down vote













    Try using Array constructor:



    let myArray = new Array(times).fill(elemnt)


    See more here Array






    share|improve this answer

















    • 1




      You don't need new for arrays.
      – Barmar
      Aug 14 at 1:06











    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',
    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%2f51831998%2fhow-to-add-same-elements-to-javascript-array-n-times%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








    up vote
    15
    down vote



    accepted










    For primitives, use .fill:






    var fruits = new Array(4).fill('Lemon');
    console.log(fruits);





    For non-primitives, don't use fill, because then all elements in the array will reference the same object in memory, so mutations to one item in the array will affect every item in the array - instead, explicitly create the object on each iteration, which can be done with Array.from:






    var fruits = Array.from(
    { length: 4 },
    () => ({ Lemon: 'Lemon' })
    );
    console.log(fruits);








    share|improve this answer

























      up vote
      15
      down vote



      accepted










      For primitives, use .fill:






      var fruits = new Array(4).fill('Lemon');
      console.log(fruits);





      For non-primitives, don't use fill, because then all elements in the array will reference the same object in memory, so mutations to one item in the array will affect every item in the array - instead, explicitly create the object on each iteration, which can be done with Array.from:






      var fruits = Array.from(
      { length: 4 },
      () => ({ Lemon: 'Lemon' })
      );
      console.log(fruits);








      share|improve this answer























        up vote
        15
        down vote



        accepted







        up vote
        15
        down vote



        accepted






        For primitives, use .fill:






        var fruits = new Array(4).fill('Lemon');
        console.log(fruits);





        For non-primitives, don't use fill, because then all elements in the array will reference the same object in memory, so mutations to one item in the array will affect every item in the array - instead, explicitly create the object on each iteration, which can be done with Array.from:






        var fruits = Array.from(
        { length: 4 },
        () => ({ Lemon: 'Lemon' })
        );
        console.log(fruits);








        share|improve this answer












        For primitives, use .fill:






        var fruits = new Array(4).fill('Lemon');
        console.log(fruits);





        For non-primitives, don't use fill, because then all elements in the array will reference the same object in memory, so mutations to one item in the array will affect every item in the array - instead, explicitly create the object on each iteration, which can be done with Array.from:






        var fruits = Array.from(
        { length: 4 },
        () => ({ Lemon: 'Lemon' })
        );
        console.log(fruits);








        var fruits = new Array(4).fill('Lemon');
        console.log(fruits);





        var fruits = new Array(4).fill('Lemon');
        console.log(fruits);





        var fruits = Array.from(
        { length: 4 },
        () => ({ Lemon: 'Lemon' })
        );
        console.log(fruits);





        var fruits = Array.from(
        { length: 4 },
        () => ({ Lemon: 'Lemon' })
        );
        console.log(fruits);






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Aug 13 at 23:56









        CertainPerformance

        69.4k143453




        69.4k143453
























            up vote
            3
            down vote













            Try using Array constructor:



            let myArray = new Array(times).fill(elemnt)


            See more here Array






            share|improve this answer

















            • 1




              You don't need new for arrays.
              – Barmar
              Aug 14 at 1:06















            up vote
            3
            down vote













            Try using Array constructor:



            let myArray = new Array(times).fill(elemnt)


            See more here Array






            share|improve this answer

















            • 1




              You don't need new for arrays.
              – Barmar
              Aug 14 at 1:06













            up vote
            3
            down vote










            up vote
            3
            down vote









            Try using Array constructor:



            let myArray = new Array(times).fill(elemnt)


            See more here Array






            share|improve this answer












            Try using Array constructor:



            let myArray = new Array(times).fill(elemnt)


            See more here Array







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Aug 14 at 0:00









            Facundo Petre

            864




            864








            • 1




              You don't need new for arrays.
              – Barmar
              Aug 14 at 1:06














            • 1




              You don't need new for arrays.
              – Barmar
              Aug 14 at 1:06








            1




            1




            You don't need new for arrays.
            – Barmar
            Aug 14 at 1:06




            You don't need new for arrays.
            – Barmar
            Aug 14 at 1:06


















            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%2f51831998%2fhow-to-add-same-elements-to-javascript-array-n-times%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







            這個網誌中的熱門文章

            Tangent Lines Diagram Along Smooth Curve

            Yusuf al-Mu'taman ibn Hud

            Zucchini