DEV Community

Cover image for 6 Different Ways To Clone An Array In JavaScript 📑
Mohammed Taha
Mohammed Taha

Posted on • Originally published at 6km.hashnode.dev

3 2

6 Different Ways To Clone An Array In JavaScript 📑

What's an Array in JavaScript?

In JavaScript, an array is a single variable that is used to store different elements. It is often used when we want to store a list of values and access them by a single variable.

In some cases, you might need to update an array without affecting the original one by making a copy of it.

Cloning an Array in JavaScript

  1. Using Array.slice() — the fastest way
var arrayToClone = [1, 2, 3]
let clone = arrayToClone.slice(0)
Enter fullscreen mode Exit fullscreen mode
  1. Using Array.concat()
var arrayToClone = [1, 2, 3]
let clone = [].concat(arrayToClone)
Enter fullscreen mode Exit fullscreen mode
  1. Using Array.map()
var arrayToClone = [1, 2, 3]
let clone = arrayToClone.map(value => value)
Enter fullscreen mode Exit fullscreen mode
  1. Spread Operator
var arrayToClone = [1, 2, 3]
let clone = [...arrayToClone]
Enter fullscreen mode Exit fullscreen mode
  1. Using JSON.stringify() and JSON.parse()
var arrayToClone = [1, 2, 3]
let clone = JSON.parse(JSON.stringify(arrayToClone))
Enter fullscreen mode Exit fullscreen mode
  1. Defining a custom clone() method

You can create your own clone() method in the prototype of your Array to use it whenever you need it.

  var arrayToClone = [1, 2, 3]

  Array.prototype.clone = function() {
     return this.map(e => Array.isArray(e) ? e.clone() : e);
  };

  // this is how to use the method
  let clone = arrayToClone.clone()

  console.log(clone)
Enter fullscreen mode Exit fullscreen mode

If you enjoyed this article, share it with your friends and colleagues!

Keep in touch,

SurveyJS custom survey software

Build Your Own Forms without Manual Coding

SurveyJS UI libraries let you build a JSON-based form management system that integrates with any backend, giving you full control over your data with no user limits. Includes support for custom question types, skip logic, an integrated CSS editor, PDF export, real-time analytics, and more.

Learn more

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more