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);    

1 comment:

Anonymous said...

Because arrays in JS are reference values, so when you try to copy it using the = it will only copy the reference to the original array and not the value of the array. To create a real copy of an array, you need to copy over the value of the array under a new value variable. That way this new array does not reference to the old array address in memory.java exception handling