How to copy or clone javascript array hack

Want to copy an array in javascript without referencing the original array objects? Try this.

Problem

If you want to copy an array in JavaScript, you will find that the 'copy' of your array will reference the original objects if you use:

var array2 = array1; 

or

var array2 = array1.slice();

Solution

Hack it using JSON.stringify()...

var array2 = JSON.parse(JSON.stringify(array1));

Now when you change the values in array2, they will not reference array1. This might not be the 'fastest' or 'most efficient' way, but it works and that's what counts in my book.

Hope this helps.

D

Comments: