Tuesday, June 2, 2020

JavaScript copy Array

To copy an Array in Javascript there are below Options

1. Using slice
     const oldArray = ["value1","value2","value3"];
     const newArray = oldArray.slice();

2. ES6 using spread(fails incase of mutli level deep Object)
     const oldArray = ["value1","value2","value3"];
     const newArray = [...oldArray ];

3. Using Array.from
     const oldArray = ["value1","value2","value3"];
     const newArray = Array.from(oldArray);    

JavaScript Clone Object

Cloning a Object in JavaScript is not going to be StraightForward especailly if the Object contians Complex Objects and is not limited to primitive types.


  1.  Use Object.assign

           var newObject = Object.assign({}, oldObject);


      2. JSON way
          var newObject =  JSON.parse(JSON.stringify(oldObject));