Strange behavior of an array filled by Array.prototype.fill()Create ArrayList from arrayHow do I check if an array includes an object in JavaScript?How to append something to an array?Deleting an element from an array in PHPHow to insert an item into an array at a specific index (JavaScript)?How do I empty an array in JavaScript?Loop through an array in JavaScriptHow to check if an object is an array?How do I remove a particular element from an array in JavaScript?For-each over an array in JavaScript?

Which US defense organization would respond to an invasion like this?

What was Bran's plan to kill the Night King?

Dangerous workplace travelling

Are there terms in German for different skull shapes?

Is any special diet a treatment of autism?

Can my 2 children, aged 10 and 12, who are US citizens, travel to the USA on expired American passports?

Why do these characters still seem to be the same age after the events of Endgame?

Hostile Divisor Numbers

Why is "breaking the mould" positively connoted?

To kill a cuckoo

Install LibreOffice-Writer Only not LibreOffice whole package

Should I simplify my writing in a foreign country?

Feasibility of lava beings?

How do I, as a DM, handle a party that decides to set up an ambush in a dungeon?

Checking if two expressions are related

Why do people keep telling me that I am a bad photographer?

Agena docking and RCS Brakes in First Man

Why didn't this character get a funeral at the end of Avengers: Endgame?

Why is my arithmetic with a long long int behaving this way?

Endgame puzzle: How to avoid stalemate and win?

Gerrymandering Puzzle - Rig the Election

Would a small hole in a Faraday cage drastically reduce its effectiveness at blocking interference?

A factorization game

What was the first story to feature the plot "the monsters were human all along"?



Strange behavior of an array filled by Array.prototype.fill()


Create ArrayList from arrayHow do I check if an array includes an object in JavaScript?How to append something to an array?Deleting an element from an array in PHPHow to insert an item into an array at a specific index (JavaScript)?How do I empty an array in JavaScript?Loop through an array in JavaScriptHow to check if an object is an array?How do I remove a particular element from an array in JavaScript?For-each over an array in JavaScript?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








4















I face something I don't understand with an array. Indeed, I created an array I have filled with empty subArrays to obtain a 2D Matrix.
But when I manipulate the array it doesn't behave as I expected.



var arr = new Array(5);
arr.fill([]);
arr[2].push("third rank item");
console.log(arr);

//[ [ 'third rank item' ],
// [ 'third rank item' ],
// [ 'third rank item' ],
// [ 'third rank item' ],
// [ 'third rank item' ] ]


Every lights on this matter will be welcomed










share|improve this question






















  • How do you expect it to behave?

    – Feathercrown
    Dec 13 '16 at 13:12






  • 2





    You're filling with the same empty array. You could instead try Array.from(new Array(5), () => []).

    – user663031
    Dec 13 '16 at 13:12












  • @torazaburo Can you explain it briefly? OP targeted the 3rd item in the outer array and pushed a string that results in pushing the string in all the internal arrays. Bit confusing.

    – Rajaprabhu Aravindasamy
    Dec 13 '16 at 13:14











  • All the internal arrays are the same array.

    – user663031
    Dec 13 '16 at 13:16











  • All the internal arrays are the same array.

    – user663031
    Dec 13 '16 at 13:16

















4















I face something I don't understand with an array. Indeed, I created an array I have filled with empty subArrays to obtain a 2D Matrix.
But when I manipulate the array it doesn't behave as I expected.



var arr = new Array(5);
arr.fill([]);
arr[2].push("third rank item");
console.log(arr);

//[ [ 'third rank item' ],
// [ 'third rank item' ],
// [ 'third rank item' ],
// [ 'third rank item' ],
// [ 'third rank item' ] ]


Every lights on this matter will be welcomed










share|improve this question






















  • How do you expect it to behave?

    – Feathercrown
    Dec 13 '16 at 13:12






  • 2





    You're filling with the same empty array. You could instead try Array.from(new Array(5), () => []).

    – user663031
    Dec 13 '16 at 13:12












  • @torazaburo Can you explain it briefly? OP targeted the 3rd item in the outer array and pushed a string that results in pushing the string in all the internal arrays. Bit confusing.

    – Rajaprabhu Aravindasamy
    Dec 13 '16 at 13:14











  • All the internal arrays are the same array.

    – user663031
    Dec 13 '16 at 13:16











  • All the internal arrays are the same array.

    – user663031
    Dec 13 '16 at 13:16













4












4








4


1






I face something I don't understand with an array. Indeed, I created an array I have filled with empty subArrays to obtain a 2D Matrix.
But when I manipulate the array it doesn't behave as I expected.



var arr = new Array(5);
arr.fill([]);
arr[2].push("third rank item");
console.log(arr);

//[ [ 'third rank item' ],
// [ 'third rank item' ],
// [ 'third rank item' ],
// [ 'third rank item' ],
// [ 'third rank item' ] ]


Every lights on this matter will be welcomed










share|improve this question














I face something I don't understand with an array. Indeed, I created an array I have filled with empty subArrays to obtain a 2D Matrix.
But when I manipulate the array it doesn't behave as I expected.



var arr = new Array(5);
arr.fill([]);
arr[2].push("third rank item");
console.log(arr);

//[ [ 'third rank item' ],
// [ 'third rank item' ],
// [ 'third rank item' ],
// [ 'third rank item' ],
// [ 'third rank item' ] ]


Every lights on this matter will be welcomed







javascript arrays






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Dec 13 '16 at 13:09









kevin ternetkevin ternet

2,634717




2,634717












  • How do you expect it to behave?

    – Feathercrown
    Dec 13 '16 at 13:12






  • 2





    You're filling with the same empty array. You could instead try Array.from(new Array(5), () => []).

    – user663031
    Dec 13 '16 at 13:12












  • @torazaburo Can you explain it briefly? OP targeted the 3rd item in the outer array and pushed a string that results in pushing the string in all the internal arrays. Bit confusing.

    – Rajaprabhu Aravindasamy
    Dec 13 '16 at 13:14











  • All the internal arrays are the same array.

    – user663031
    Dec 13 '16 at 13:16











  • All the internal arrays are the same array.

    – user663031
    Dec 13 '16 at 13:16

















  • How do you expect it to behave?

    – Feathercrown
    Dec 13 '16 at 13:12






  • 2





    You're filling with the same empty array. You could instead try Array.from(new Array(5), () => []).

    – user663031
    Dec 13 '16 at 13:12












  • @torazaburo Can you explain it briefly? OP targeted the 3rd item in the outer array and pushed a string that results in pushing the string in all the internal arrays. Bit confusing.

    – Rajaprabhu Aravindasamy
    Dec 13 '16 at 13:14











  • All the internal arrays are the same array.

    – user663031
    Dec 13 '16 at 13:16











  • All the internal arrays are the same array.

    – user663031
    Dec 13 '16 at 13:16
















How do you expect it to behave?

– Feathercrown
Dec 13 '16 at 13:12





How do you expect it to behave?

– Feathercrown
Dec 13 '16 at 13:12




2




2





You're filling with the same empty array. You could instead try Array.from(new Array(5), () => []).

– user663031
Dec 13 '16 at 13:12






You're filling with the same empty array. You could instead try Array.from(new Array(5), () => []).

– user663031
Dec 13 '16 at 13:12














@torazaburo Can you explain it briefly? OP targeted the 3rd item in the outer array and pushed a string that results in pushing the string in all the internal arrays. Bit confusing.

– Rajaprabhu Aravindasamy
Dec 13 '16 at 13:14





@torazaburo Can you explain it briefly? OP targeted the 3rd item in the outer array and pushed a string that results in pushing the string in all the internal arrays. Bit confusing.

– Rajaprabhu Aravindasamy
Dec 13 '16 at 13:14













All the internal arrays are the same array.

– user663031
Dec 13 '16 at 13:16





All the internal arrays are the same array.

– user663031
Dec 13 '16 at 13:16













All the internal arrays are the same array.

– user663031
Dec 13 '16 at 13:16





All the internal arrays are the same array.

– user663031
Dec 13 '16 at 13:16












7 Answers
7






active

oldest

votes


















5














This is the same old problem with arrays (and objects in general) being references rather than values.



Specifically, when you do arr.fill([]), you are taking that one single empty array and using that to fill the parent one.



It's like saying:



var arr = new Array(5);
arr[0] = arr[1] = arr[2] = arr[3] = arr[4] = [];


They all refer to the same array! So when you then go on to modify one of them, it looks like they're all modified (but really it's still the same one)



Unfortunately there's no simple way to assign an empty array to each one. You could do something like:



Array.apply(null, Array(5)).map(function() return [];);


Essentially, create an (initialised) empty array of length 5 and map each (empty) value to a new [].



EDIT: Seems like I'm stuck in old times. As per @torazaburo's comment, you can use Array.from instead of Array.apply(null, Array(5)).map, like so:



Array.from( new Array(5), function() return []; );





share|improve this answer























  • Thank's for the clear explanation and smart solution

    – kevin ternet
    Dec 13 '16 at 13:56


















1














As you can notice using array.fill you're filling the array with a reference to the same array,



if you want to instantiate each array index to an empty array a normal while loop will do:






var arr = [];
var n = 5
while(n--)
arr[n] = []

arr[2].push("third rank item");
console.log(arr);





Option 2:

if you have lodash package available, you can also use _.map as this is specificaly designed to loop through a sparse array (native map will skip non init values)






var arr =_.map(new Array(5), (x => []))

arr[2].push("third rank item");
console.log(arr)

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.2/lodash.min.js"></script>








share|improve this answer

























  • Thank's for giving an extra solution with lodash

    – kevin ternet
    Dec 13 '16 at 13:54


















1














The eleventh line of the ECMA doc of Array.prototype.fill is clearly giving the reason for the mystery.




Repeat, while k < final



Let Pk be ToString(k).



Let setStatus be Set(O, Pk, value, true).



ReturnIfAbrupt(setStatus).



Increase k by 1.




Here "value" is just a reference received. And they are setting it as a property to array directly. That means all the filled arrays are just reference to a single array object.






share|improve this answer


















  • 1





    Thank's. You make me very well aware of the importance of reading documentation

    – kevin ternet
    Dec 13 '16 at 13:52



















1














It's happens cause of reference. Array is a type of object and object works on their references when you fill your array with [] or new Array() fill run only ones and put the same array in all indexes that's why when you update an sub-array all are updated.



Solution:



let arr = new Array(5).fill(0).map(ele => ele = []);
arr[2].push("something");



OR



let arr = Array.of([], [], [], []);
arr[2].push("something");



Result: as expected only 2 index of arr is updated.






share|improve this answer

























  • Quick to write and easy to understand. Thanks

    – kevin ternet
    Dec 13 '16 at 13:51











  • you are welcome.

    – Umair Ahmed
    Dec 13 '16 at 14:18


















0














Try this ,this is quick solution for you in one line.






var arr = new Array(5);
arr = Array.from(arr, x => []);
arr[2].push("third rank item");
console.log(arr);








share|improve this answer






























    0














    You can try this,






    var arr = new Array(5);
    var i = 0;
    while (i < arr.length)
    arr.fill([], i++);
    arr[2].push("third rank item");
    console.log(arr);








    share|improve this answer
































      0














      With ES6 I recommend this method to create 2 or multidimensional arrays:



      // create an M x N dimension grid and fill it with 0's
      const myArray = [...Array(M)].map(r => [...Array(N)].map(r => 0));





      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%2f41121982%2fstrange-behavior-of-an-array-filled-by-array-prototype-fill%23new-answer', 'question_page');

        );

        Post as a guest















        Required, but never shown

























        7 Answers
        7






        active

        oldest

        votes








        7 Answers
        7






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes









        5














        This is the same old problem with arrays (and objects in general) being references rather than values.



        Specifically, when you do arr.fill([]), you are taking that one single empty array and using that to fill the parent one.



        It's like saying:



        var arr = new Array(5);
        arr[0] = arr[1] = arr[2] = arr[3] = arr[4] = [];


        They all refer to the same array! So when you then go on to modify one of them, it looks like they're all modified (but really it's still the same one)



        Unfortunately there's no simple way to assign an empty array to each one. You could do something like:



        Array.apply(null, Array(5)).map(function() return [];);


        Essentially, create an (initialised) empty array of length 5 and map each (empty) value to a new [].



        EDIT: Seems like I'm stuck in old times. As per @torazaburo's comment, you can use Array.from instead of Array.apply(null, Array(5)).map, like so:



        Array.from( new Array(5), function() return []; );





        share|improve this answer























        • Thank's for the clear explanation and smart solution

          – kevin ternet
          Dec 13 '16 at 13:56















        5














        This is the same old problem with arrays (and objects in general) being references rather than values.



        Specifically, when you do arr.fill([]), you are taking that one single empty array and using that to fill the parent one.



        It's like saying:



        var arr = new Array(5);
        arr[0] = arr[1] = arr[2] = arr[3] = arr[4] = [];


        They all refer to the same array! So when you then go on to modify one of them, it looks like they're all modified (but really it's still the same one)



        Unfortunately there's no simple way to assign an empty array to each one. You could do something like:



        Array.apply(null, Array(5)).map(function() return [];);


        Essentially, create an (initialised) empty array of length 5 and map each (empty) value to a new [].



        EDIT: Seems like I'm stuck in old times. As per @torazaburo's comment, you can use Array.from instead of Array.apply(null, Array(5)).map, like so:



        Array.from( new Array(5), function() return []; );





        share|improve this answer























        • Thank's for the clear explanation and smart solution

          – kevin ternet
          Dec 13 '16 at 13:56













        5












        5








        5







        This is the same old problem with arrays (and objects in general) being references rather than values.



        Specifically, when you do arr.fill([]), you are taking that one single empty array and using that to fill the parent one.



        It's like saying:



        var arr = new Array(5);
        arr[0] = arr[1] = arr[2] = arr[3] = arr[4] = [];


        They all refer to the same array! So when you then go on to modify one of them, it looks like they're all modified (but really it's still the same one)



        Unfortunately there's no simple way to assign an empty array to each one. You could do something like:



        Array.apply(null, Array(5)).map(function() return [];);


        Essentially, create an (initialised) empty array of length 5 and map each (empty) value to a new [].



        EDIT: Seems like I'm stuck in old times. As per @torazaburo's comment, you can use Array.from instead of Array.apply(null, Array(5)).map, like so:



        Array.from( new Array(5), function() return []; );





        share|improve this answer













        This is the same old problem with arrays (and objects in general) being references rather than values.



        Specifically, when you do arr.fill([]), you are taking that one single empty array and using that to fill the parent one.



        It's like saying:



        var arr = new Array(5);
        arr[0] = arr[1] = arr[2] = arr[3] = arr[4] = [];


        They all refer to the same array! So when you then go on to modify one of them, it looks like they're all modified (but really it's still the same one)



        Unfortunately there's no simple way to assign an empty array to each one. You could do something like:



        Array.apply(null, Array(5)).map(function() return [];);


        Essentially, create an (initialised) empty array of length 5 and map each (empty) value to a new [].



        EDIT: Seems like I'm stuck in old times. As per @torazaburo's comment, you can use Array.from instead of Array.apply(null, Array(5)).map, like so:



        Array.from( new Array(5), function() return []; );






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Dec 13 '16 at 13:16









        Niet the Dark AbsolNiet the Dark Absol

        262k57368480




        262k57368480












        • Thank's for the clear explanation and smart solution

          – kevin ternet
          Dec 13 '16 at 13:56

















        • Thank's for the clear explanation and smart solution

          – kevin ternet
          Dec 13 '16 at 13:56
















        Thank's for the clear explanation and smart solution

        – kevin ternet
        Dec 13 '16 at 13:56





        Thank's for the clear explanation and smart solution

        – kevin ternet
        Dec 13 '16 at 13:56













        1














        As you can notice using array.fill you're filling the array with a reference to the same array,



        if you want to instantiate each array index to an empty array a normal while loop will do:






        var arr = [];
        var n = 5
        while(n--)
        arr[n] = []

        arr[2].push("third rank item");
        console.log(arr);





        Option 2:

        if you have lodash package available, you can also use _.map as this is specificaly designed to loop through a sparse array (native map will skip non init values)






        var arr =_.map(new Array(5), (x => []))

        arr[2].push("third rank item");
        console.log(arr)

        <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.2/lodash.min.js"></script>








        share|improve this answer

























        • Thank's for giving an extra solution with lodash

          – kevin ternet
          Dec 13 '16 at 13:54















        1














        As you can notice using array.fill you're filling the array with a reference to the same array,



        if you want to instantiate each array index to an empty array a normal while loop will do:






        var arr = [];
        var n = 5
        while(n--)
        arr[n] = []

        arr[2].push("third rank item");
        console.log(arr);





        Option 2:

        if you have lodash package available, you can also use _.map as this is specificaly designed to loop through a sparse array (native map will skip non init values)






        var arr =_.map(new Array(5), (x => []))

        arr[2].push("third rank item");
        console.log(arr)

        <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.2/lodash.min.js"></script>








        share|improve this answer

























        • Thank's for giving an extra solution with lodash

          – kevin ternet
          Dec 13 '16 at 13:54













        1












        1








        1







        As you can notice using array.fill you're filling the array with a reference to the same array,



        if you want to instantiate each array index to an empty array a normal while loop will do:






        var arr = [];
        var n = 5
        while(n--)
        arr[n] = []

        arr[2].push("third rank item");
        console.log(arr);





        Option 2:

        if you have lodash package available, you can also use _.map as this is specificaly designed to loop through a sparse array (native map will skip non init values)






        var arr =_.map(new Array(5), (x => []))

        arr[2].push("third rank item");
        console.log(arr)

        <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.2/lodash.min.js"></script>








        share|improve this answer















        As you can notice using array.fill you're filling the array with a reference to the same array,



        if you want to instantiate each array index to an empty array a normal while loop will do:






        var arr = [];
        var n = 5
        while(n--)
        arr[n] = []

        arr[2].push("third rank item");
        console.log(arr);





        Option 2:

        if you have lodash package available, you can also use _.map as this is specificaly designed to loop through a sparse array (native map will skip non init values)






        var arr =_.map(new Array(5), (x => []))

        arr[2].push("third rank item");
        console.log(arr)

        <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.2/lodash.min.js"></script>








        var arr = [];
        var n = 5
        while(n--)
        arr[n] = []

        arr[2].push("third rank item");
        console.log(arr);





        var arr = [];
        var n = 5
        while(n--)
        arr[n] = []

        arr[2].push("third rank item");
        console.log(arr);





        var arr =_.map(new Array(5), (x => []))

        arr[2].push("third rank item");
        console.log(arr)

        <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.2/lodash.min.js"></script>





        var arr =_.map(new Array(5), (x => []))

        arr[2].push("third rank item");
        console.log(arr)

        <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.2/lodash.min.js"></script>






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Dec 13 '16 at 13:24

























        answered Dec 13 '16 at 13:17









        maiomanmaioman

        11.7k32034




        11.7k32034












        • Thank's for giving an extra solution with lodash

          – kevin ternet
          Dec 13 '16 at 13:54

















        • Thank's for giving an extra solution with lodash

          – kevin ternet
          Dec 13 '16 at 13:54
















        Thank's for giving an extra solution with lodash

        – kevin ternet
        Dec 13 '16 at 13:54





        Thank's for giving an extra solution with lodash

        – kevin ternet
        Dec 13 '16 at 13:54











        1














        The eleventh line of the ECMA doc of Array.prototype.fill is clearly giving the reason for the mystery.




        Repeat, while k < final



        Let Pk be ToString(k).



        Let setStatus be Set(O, Pk, value, true).



        ReturnIfAbrupt(setStatus).



        Increase k by 1.




        Here "value" is just a reference received. And they are setting it as a property to array directly. That means all the filled arrays are just reference to a single array object.






        share|improve this answer


















        • 1





          Thank's. You make me very well aware of the importance of reading documentation

          – kevin ternet
          Dec 13 '16 at 13:52
















        1














        The eleventh line of the ECMA doc of Array.prototype.fill is clearly giving the reason for the mystery.




        Repeat, while k < final



        Let Pk be ToString(k).



        Let setStatus be Set(O, Pk, value, true).



        ReturnIfAbrupt(setStatus).



        Increase k by 1.




        Here "value" is just a reference received. And they are setting it as a property to array directly. That means all the filled arrays are just reference to a single array object.






        share|improve this answer


















        • 1





          Thank's. You make me very well aware of the importance of reading documentation

          – kevin ternet
          Dec 13 '16 at 13:52














        1












        1








        1







        The eleventh line of the ECMA doc of Array.prototype.fill is clearly giving the reason for the mystery.




        Repeat, while k < final



        Let Pk be ToString(k).



        Let setStatus be Set(O, Pk, value, true).



        ReturnIfAbrupt(setStatus).



        Increase k by 1.




        Here "value" is just a reference received. And they are setting it as a property to array directly. That means all the filled arrays are just reference to a single array object.






        share|improve this answer













        The eleventh line of the ECMA doc of Array.prototype.fill is clearly giving the reason for the mystery.




        Repeat, while k < final



        Let Pk be ToString(k).



        Let setStatus be Set(O, Pk, value, true).



        ReturnIfAbrupt(setStatus).



        Increase k by 1.




        Here "value" is just a reference received. And they are setting it as a property to array directly. That means all the filled arrays are just reference to a single array object.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Dec 13 '16 at 13:26









        Rajaprabhu AravindasamyRajaprabhu Aravindasamy

        56.3k1269104




        56.3k1269104







        • 1





          Thank's. You make me very well aware of the importance of reading documentation

          – kevin ternet
          Dec 13 '16 at 13:52













        • 1





          Thank's. You make me very well aware of the importance of reading documentation

          – kevin ternet
          Dec 13 '16 at 13:52








        1




        1





        Thank's. You make me very well aware of the importance of reading documentation

        – kevin ternet
        Dec 13 '16 at 13:52






        Thank's. You make me very well aware of the importance of reading documentation

        – kevin ternet
        Dec 13 '16 at 13:52












        1














        It's happens cause of reference. Array is a type of object and object works on their references when you fill your array with [] or new Array() fill run only ones and put the same array in all indexes that's why when you update an sub-array all are updated.



        Solution:



        let arr = new Array(5).fill(0).map(ele => ele = []);
        arr[2].push("something");



        OR



        let arr = Array.of([], [], [], []);
        arr[2].push("something");



        Result: as expected only 2 index of arr is updated.






        share|improve this answer

























        • Quick to write and easy to understand. Thanks

          – kevin ternet
          Dec 13 '16 at 13:51











        • you are welcome.

          – Umair Ahmed
          Dec 13 '16 at 14:18















        1














        It's happens cause of reference. Array is a type of object and object works on their references when you fill your array with [] or new Array() fill run only ones and put the same array in all indexes that's why when you update an sub-array all are updated.



        Solution:



        let arr = new Array(5).fill(0).map(ele => ele = []);
        arr[2].push("something");



        OR



        let arr = Array.of([], [], [], []);
        arr[2].push("something");



        Result: as expected only 2 index of arr is updated.






        share|improve this answer

























        • Quick to write and easy to understand. Thanks

          – kevin ternet
          Dec 13 '16 at 13:51











        • you are welcome.

          – Umair Ahmed
          Dec 13 '16 at 14:18













        1












        1








        1







        It's happens cause of reference. Array is a type of object and object works on their references when you fill your array with [] or new Array() fill run only ones and put the same array in all indexes that's why when you update an sub-array all are updated.



        Solution:



        let arr = new Array(5).fill(0).map(ele => ele = []);
        arr[2].push("something");



        OR



        let arr = Array.of([], [], [], []);
        arr[2].push("something");



        Result: as expected only 2 index of arr is updated.






        share|improve this answer















        It's happens cause of reference. Array is a type of object and object works on their references when you fill your array with [] or new Array() fill run only ones and put the same array in all indexes that's why when you update an sub-array all are updated.



        Solution:



        let arr = new Array(5).fill(0).map(ele => ele = []);
        arr[2].push("something");



        OR



        let arr = Array.of([], [], [], []);
        arr[2].push("something");



        Result: as expected only 2 index of arr is updated.







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Jan 20 '17 at 12:40

























        answered Dec 13 '16 at 13:45









        Umair AhmedUmair Ahmed

        2,64021727




        2,64021727












        • Quick to write and easy to understand. Thanks

          – kevin ternet
          Dec 13 '16 at 13:51











        • you are welcome.

          – Umair Ahmed
          Dec 13 '16 at 14:18

















        • Quick to write and easy to understand. Thanks

          – kevin ternet
          Dec 13 '16 at 13:51











        • you are welcome.

          – Umair Ahmed
          Dec 13 '16 at 14:18
















        Quick to write and easy to understand. Thanks

        – kevin ternet
        Dec 13 '16 at 13:51





        Quick to write and easy to understand. Thanks

        – kevin ternet
        Dec 13 '16 at 13:51













        you are welcome.

        – Umair Ahmed
        Dec 13 '16 at 14:18





        you are welcome.

        – Umair Ahmed
        Dec 13 '16 at 14:18











        0














        Try this ,this is quick solution for you in one line.






        var arr = new Array(5);
        arr = Array.from(arr, x => []);
        arr[2].push("third rank item");
        console.log(arr);








        share|improve this answer



























          0














          Try this ,this is quick solution for you in one line.






          var arr = new Array(5);
          arr = Array.from(arr, x => []);
          arr[2].push("third rank item");
          console.log(arr);








          share|improve this answer

























            0












            0








            0







            Try this ,this is quick solution for you in one line.






            var arr = new Array(5);
            arr = Array.from(arr, x => []);
            arr[2].push("third rank item");
            console.log(arr);








            share|improve this answer













            Try this ,this is quick solution for you in one line.






            var arr = new Array(5);
            arr = Array.from(arr, x => []);
            arr[2].push("third rank item");
            console.log(arr);








            var arr = new Array(5);
            arr = Array.from(arr, x => []);
            arr[2].push("third rank item");
            console.log(arr);





            var arr = new Array(5);
            arr = Array.from(arr, x => []);
            arr[2].push("third rank item");
            console.log(arr);






            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Dec 31 '16 at 6:34









            vijayvijay

            881515




            881515





















                0














                You can try this,






                var arr = new Array(5);
                var i = 0;
                while (i < arr.length)
                arr.fill([], i++);
                arr[2].push("third rank item");
                console.log(arr);








                share|improve this answer





























                  0














                  You can try this,






                  var arr = new Array(5);
                  var i = 0;
                  while (i < arr.length)
                  arr.fill([], i++);
                  arr[2].push("third rank item");
                  console.log(arr);








                  share|improve this answer



























                    0












                    0








                    0







                    You can try this,






                    var arr = new Array(5);
                    var i = 0;
                    while (i < arr.length)
                    arr.fill([], i++);
                    arr[2].push("third rank item");
                    console.log(arr);








                    share|improve this answer















                    You can try this,






                    var arr = new Array(5);
                    var i = 0;
                    while (i < arr.length)
                    arr.fill([], i++);
                    arr[2].push("third rank item");
                    console.log(arr);








                    var arr = new Array(5);
                    var i = 0;
                    while (i < arr.length)
                    arr.fill([], i++);
                    arr[2].push("third rank item");
                    console.log(arr);





                    var arr = new Array(5);
                    var i = 0;
                    while (i < arr.length)
                    arr.fill([], i++);
                    arr[2].push("third rank item");
                    console.log(arr);






                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Dec 31 '16 at 6:35

























                    answered Dec 31 '16 at 6:08









                    vijayvijay

                    881515




                    881515





















                        0














                        With ES6 I recommend this method to create 2 or multidimensional arrays:



                        // create an M x N dimension grid and fill it with 0's
                        const myArray = [...Array(M)].map(r => [...Array(N)].map(r => 0));





                        share|improve this answer





























                          0














                          With ES6 I recommend this method to create 2 or multidimensional arrays:



                          // create an M x N dimension grid and fill it with 0's
                          const myArray = [...Array(M)].map(r => [...Array(N)].map(r => 0));





                          share|improve this answer



























                            0












                            0








                            0







                            With ES6 I recommend this method to create 2 or multidimensional arrays:



                            // create an M x N dimension grid and fill it with 0's
                            const myArray = [...Array(M)].map(r => [...Array(N)].map(r => 0));





                            share|improve this answer















                            With ES6 I recommend this method to create 2 or multidimensional arrays:



                            // create an M x N dimension grid and fill it with 0's
                            const myArray = [...Array(M)].map(r => [...Array(N)].map(r => 0));






                            share|improve this answer














                            share|improve this answer



                            share|improve this answer








                            edited Mar 23 at 1:28









                            Nino Filiu

                            3,35341631




                            3,35341631










                            answered Mar 23 at 1:06









                            Joseph WonJoseph Won

                            1




                            1



























                                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%2f41121982%2fstrange-behavior-of-an-array-filled-by-array-prototype-fill%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

                                Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

                                Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

                                Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript