0

I have constant elements array named items and want to copy it to arr2.

How to copy constantant elements array to another array?

I tried to use splice but it didn't work.

window.onload="rvalue()"
var tempimages = [];
var arr2=[];

function rvalue() 
{
    const items = [  
        { label: '1', url: '1.jpg'  },
        { label: '2', url: '2.jpg'  },
        { label: '3', url: '3.jpg'  },
        { label: '4', url: '4.jpg'  },
        { label: '5', url: '5.jpg'  },
        { label: '6', url: '6.jpg'  },
        { label: '7', url: '7.jpg'  },
        { label: '8', url: '8.jpg'  },
        { label: '9', url: '9.jpg'  },
        { label: '10', url: '10.jpg'},
        { label: '11', url: '11.jpg'},
        { label: '12', url: '12.jpg'},


    ]

    ptags = document.querySelectorAll('[name="values"]');
    arr2 = items.splice(0); 

    for (let index = 0; index < 4;index++) 
    {
        randomIndex = Math.floor(Math.random() * items.length),var item2[index]=['item.label','item'];

        var item2[index]=['item.label','item'];

        item = items[randomIndex];
        ptags[index].textContent = item.label;
        tempimages.push(item); 
    }

    console.log(item2);
}
ironman
  • 3
  • 6
  • Possible duplicate of [JavaScript: How to join / combine two arrays to concatenate into one array?](https://stackoverflow.com/questions/3975170/javascript-how-to-join-combine-two-arrays-to-concatenate-into-one-array) – Calvin Nunes Sep 19 '18 at 11:43
  • @calvin-nunes im not trying to concatenate 2 arrays, iwant to duplicate a conatant items named items – ironman Sep 19 '18 at 11:45
  • ok, but what is the problem with `arr2 = arr2.concat(items)` that is what the duplicate question have as answer? it works... you'll have `arr2` with same values as `items` – Calvin Nunes Sep 19 '18 at 11:47
  • 2
    Possible duplicate of [How do you clone an Array of Objects in Javascript?](https://stackoverflow.com/questions/597588/how-do-you-clone-an-array-of-objects-in-javascript) – BeNdErR Sep 19 '18 at 11:51

1 Answers1

1

If you want to just copy them you can do:

const arr2 = [...items] https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Operators/Spread_syntax

Michel Vorwieger
  • 692
  • 5
  • 14