MOCKSTACKS
EN
Questions And Answers

More Tutorials









Javascript cloning an array

Sometimes, you need to work with an array while ensuring you don't modify the original. Instead of a clone method, arrays have a slice method that lets you perform a shallow copy of any part of an array. Keep in mind that this only clones the first level. This works well with primitive types, like numbers and strings, but not objects.

To shallow-clone an array (i.e. have a new array instance but with the same elements), you can use the following one-liner:


var clone = arrayToClone.slice();

This calls the built-in JavaScript Array.prototype.slice method. If you pass arguments to slice, you can get more complicated behaviors that create shallow clones of only part of an array, but for our purposes just calling slice() will create a shallow copy of the entire array.

All method used to convert array like objects to array are applicable to clone an array:


arrayToClone = [1, 2, 3, 4, 5];
clone1 = Array.from(arrayToClone);
clone2 = Array.of(...arrayToClone);
clone3 = [...arrayToClone]

arrayToClone = [1, 2, 3, 4, 5];
clone1 = Array.prototype.slice.call(arrayToClone);
clone2 = [].slice.call(arrayToClone);


Conclusion

In this page (written and validated by ) you learned about Javascript cloning an array . What's Next? If you are interested in completing Javascript tutorial, your next topic will be learning about: Javascript Concatenating Arrays.



Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue: mockstacks@gmail.com.


Share On:


Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using Mockstacks.com, you agree to have read and accepted our terms of use, cookies and privacy policy.