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,

Sentry blog image

How to reduce TTFB

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, we’ll see how we can identify what makes our TTFB high so we can fix it.

Read more

Top comments (0)

AWS GenAI LIVE!

GenAI LIVE! is a dynamic live-streamed show exploring how AWS and our partners are helping organizations unlock real value with generative AI.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❀️