Search code examples
javascriptjqueryarraysclone

Clone array of objects into itself


This is my source array (e.g. with 20 elements):

var myArray= $('.my-selector').clone().toArray();

I want to clone the whole array into itself. The new array should have 40 elements (each element is existing "twice"). Like this:

myNewArray = myArray.concat($('.my-selector').clone().toArray())

But it seems that the new arrays elements are references to the original and no real clones.


Solution

  • Updated answer.

    @JKB, I have updated my answer based on your recent comment on my old answer. I think the code you have posted in your question is actually working fine. I am using 3 elements to demo this, instead of the original 20, but the same logic applies.

    I have quoted you in code comments in the code snippets, from your original question, as well as your recent comment on my old answer. Please read through them.

    // "The source are jQuery objects" ~ JKB
    var source = $('.my-selector')
    
    /* "This source should be cloned into an array" - JKB
    I am Copying this from your original code. */
    var myArray = $('.my-selector').clone().toArray()
    
    /* "Now i want to increase the arrays size by copying its content into itself, after that the array should contain 20 objects (each object twice)" - JKB
    Our array should contain 6, since we're cloning 3 elements onto itself. Copying this again from your original code. */
    var myNewArray = myArray.concat($('.my-selector').clone().toArray())
    
    // "BUT: Now this objects should be inserted back into another DOM place (not into their original place)." - JKB
    $('#anotherPlace').append(myNewArray)
    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
    
    <div class="my-selector">first</div>
    <div class="my-selector">second</div>
    <div class="my-selector">third</div>
    <div id="anotherPlace" style="background:red"></div>

    But it seems that the new arrays elements are references to the original and no real clones.

    They aren't, that's why we see 2 copies of each - first, second and third in the red background div. Is this what you were looking for, or did I miss something obvious?