JavaScript: Clone an Array & Object By Examples

Observation

JavaScript provides several methods to copy, clone, or duplicate arrays and objects. In this tutorial, we would love to share with you the simplest, different and easiest way to copy, clone or duplicate an array and objects.

.We share the different, simplest and easy methods to duplicate, copy or clone an array and objects.

There are at least 5 (!) ways to clone an array

There are at least 5 (!) ways to clone an array:

Here you will learn method step by step, Let’s take a first method

Spread Operator(fastest) Way to Clone array

var arr = [1,2,3,4,5];

// Spread Operator  
var arr1 = [...arr];

Slice Operator Clone array

var arr = [1,2,3,4,5];

// Slice Operator
var arr2 = arr.slice();

Using Concat Clone array

var arr = [1,2,3,4,5];

// Concat
var arr3 = [].concat(arr)

Clone array using From() method

var arr = [1,2,3,4,5];

// Array.from()
var arr4 = Array.from(arr);

Clone Array Using For loop

// For loop
function arr5(arr) {
  let newArr = [];
  for(let i=0; i<arr.length; ++i) {
      newArr[i] = arr[i];
  }
  return arr;
}

Note: All of the above are shallow copies. If the original array is multi-dimensional there will be problems since you need a deep copy.

Deep Copy Array

You can solve this by serializing the entire array to JSON and then de-serializing it, but this results in bad performance and doesn’t work with special objects.

// Deep copy
const dupArray = JSON.parse(JSON.stringify(arr))

How to Copy Objects in JavaScript?

Answer: Using the javascript methods to Clone(Copy) Objects with examples

Fast cloning with data loss – JSON.parse/stringify

var obj = {
  name: 'string',
  number: 123,
  email : '[email protected]'
  bool: false,
  nul: null,
  date: new Date(),  // stringified
}
console.log(obj);
console.log(typeof obj.date); 

var clone = JSON.parse(JSON.stringify(obj));
console.log(clone);

Using the assign() method to clone the object

Object.assign () or Spread syntax can be used for a copy but it will be the shallow copy.

var orgObj= {
  name: 'Dell',
  laptop: {
    color: 'black'
  }
}
var copiedObj = Object.assign({}, orgObj)

orgObj.name = 'Dell I5'
orgObj.car.color = 'BLUE'

copiedObj.name //Dell
copiedObj.laptop.color //black

Conclusion

In this clone, copy or duplicate arrays and objects tutorial, you have learned how to clone, copy or duplicate javascript arrays and objects using the simplest methods.

If you have any questions or thoughts to share, use the comment form below to reach us.

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *