How to copy an array in JavaScript

How to copy an array in JavaScript

In this post we will give you information about How to copy an array in JavaScript. Hear we will give you detail about How to copy an array in JavaScriptAnd how to use it also give you demo for it if it is necessary.

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 copyconsole.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 copyconsole.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.

Hope this code and post will helped you for implement How to copy an array in JavaScript. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs

For More Info See :: laravel And github

We're accepting well-written guest posts and this is a great opportunity to collaborate : Contact US