6 Different Ways To Clone An Array In JavaScript ๐Ÿ“‘

6 Different Ways To Clone An Array In JavaScript ๐Ÿ“‘

ยท

2 min read

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)
    
  2. Using Array.concat()

    var arrayToClone = [1, 2, 3]
    let clone = [].concat(arrayToClone)
    
  3. Using Array.map()

    var arrayToClone = [1, 2, 3]
    let clone = arrayToClone.map(value => value)
    
  4. Spread Operator

    var arrayToClone = [1, 2, 3]
    let clone = [...arrayToClone]
    
  5. Using JSON.stringify() and JSON.parse()

    var arrayToClone = [1, 2, 3]
    let clone = JSON.parse(JSON.stringify(arrayToClone))
    
  6. 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)
    

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

Keep in touch,

ย