Udemy

Javascript deep Copy Array (Clone Javascript array without reference)

Thursday, September 11, 2014 0 Comments A+ a-

Today i saw a SO question, in which the OP was asking about how to clone a javascript array in a variable so that it does not have reference tot the original array.


Here is the scenario:


var fruit = function (name){
    this.name = name;
}
var fruits = [];
fruits.push(new fruit('apple'));
fruits.push(new fruit('banana'));
fruits.push(new fruit('organge'));

var fruits2 = fruits;
fruits2.length = 0;

Now in the above when we assign fruits to fruits2, fruits2 actually has the reference of fruits, after that line if you see we are emptying the fruits2 array by setting its lenght to 0. But it will also make fruits array empty as well.


See here in the JSFiddle DEMO:

Now we have to make a way to do deep clone of array so that it not refers to original array, we can do it using slice() function of javascript.

Summary of slice():

The slice() method returns a shallow copy of a portion of an array into a new array object.

Description:

slice does not alter the original array, but returns a new "one level deep" copy that contains copies of the elements sliced from the original array. Elements of the original array are copied into the new array as follows:
  • For object references (and not the actual object), slice copies object references into the new array. Both the original and new array refer to the same object. If a referenced object changes, the changes are visible to both the new and original arrays.
  • For strings and numbers (not String and Number objects), slice copies strings and numbers into the new array. Changes to the string or number in one array does not affect the other array.

EXAMPLE:




// Our good friend the citrus from fruits example
var fruits = ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango'];
var citrus = fruits.slice(1, 3);

// puts --> ['Orange','Lemon']

When we write slice(0)  , it returns the complete array shallow copy in return so our modified code will be:

 

var fruit = function (name){
    this.name = name;
}
var fruits = [];
fruits.push(new fruit('apple'));
fruits.push(new fruit('banana'));
fruits.push(new fruit('organge'));

var fruits2 = fruits.slice(0);
fruits2.length = 0;
console.log(fruits);

Here is the UPDATED FIDDLE  in which you can see it live working.
Coursera - Hundreds of Specializations and courses in business, computer science, data science, and more