How to copy an array in JavaScript
In this tutorial, we are going to learn about two different ways to copy or clone an array in JavaScript.
Slice method
The slice()
method returns the copy of an array without modifying the original array in JavaScript.
Example:
const users = ['jim','raj','king'];
const users2 = users.slice() // creates the copy
console.log(users2) // ['jim','raj','king'];
Es6 spread operator (…)
In es6, we have a spread operator(…) which helps us to create a duplicate copy of an array.
Example:
const users = ['jim','raj','king'];
const users2 = [...users]// creates the copy
console.log(users2) // ['jim','raj','king'];
In the above code, we have added ...users
inside users2
array so that all elements present inside the users
array are copied to the users2
array.