JavaScript Clone Array Examples

Today, We want to share with you JavaScript Clone Array Examples.In this post we will show you javascript – how to clone Array without reference, hear for Cloning JavaScript Array in Multiple Ways we will give you demo and example for implement.In this post, we will learn about write a javascript function to clone an array with an example.

JavaScript Clone Array Examples

There are the Following The simple About JavaScript Clone Array Examples Full Information With Example and source code.

As I will cover this Post with live Working example to develop Fastest way to duplicate an array in JavaScript, so the How to clone a Javascript Array of Objects? for this example is following below.

Using ES6 Spread operator

var productsObject = [...productsArray];

Using Slice

var productsObject = productsArray.slice();

Using Concat

var productsObject = [].concat(productsArray);

Using Array apply

var productsObject = Array.apply(undefined, productsArray);

Using an Array from

var productsObject = Array.from(productsArray);

Using An Array map

var productsObject = Array.apply(undefined, productsArray);

Using Using loop index

var productsObject = new Array(productsArray.length);
for (var i = 0, l = productsArray.length; i < l; i++) {
  productsObject[i] = productsArray[i];
}

Using Push using loop

var productsObject = [];
for (var i = 0, l = productsArray.length; i < l; i++) {
  productsObject.push(productsArray[i]);
}

Using unshift

var productsObject = [];
for (var i = productsArray.length; i--;) {
  productsObject.unshift(productsArray[i]);
}

Using Serialising then de-serializing

var productsObject = JSON.parse(JSON.stringify(productsArray));

clone an object in JavaScript

const product = {
  string: 'string',
  number: 123,
  bool: false,
  nul: null,
  date: new Date(),  // stringified
  undef: undefined,  // lost
  inf: Infinity,  // forced to 'null'
  re: /.*/,  // lost
}
console.log(product);
console.log(typeof product.date);  // Date object
const clone = JSON.parse(JSON.stringify(product));
console.log(clone);
console.log(typeof clone.date);  // result of .toISOString()
Web Programming Tutorials Example with Demo

Read :

Summary

You can also read about AngularJS, ASP.NET, VueJs, PHP.

I hope you get an idea about JavaScript Clone Array Examples.
I would like to have feedback on my infinityknow.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.

Leave a Comment