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

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,

Top comments (0)