srph
srph

Reputation: 1322

array.concat vs angular.copy

I've noticed that [].concat() performs similarly to angular.copy() with arrays. For instance,

var x = [5, 2];
var y = [].concat(x);
// y = [5, 2]

x = [2, 3];
// y = [5, 2]

var z = angular.copy(x);
// z = [2, 3];

x = [6, 9];
// z = [2, 3];

Is there a key difference between [].concat() and angular.copy(src,[dest])?

Upvotes: 0

Views: 982

Answers (2)

PSL
PSL

Reputation: 123739

angular.copy performs a deep copy of the source and places it on the destination (Both the arrays of source and dest and its contents, even reference types, points to different reference location). But when you do [].concat (Both the arrays of source and dest points to different reference and its reference type contents points to the same reference), it just returns a new array, so only think that is similar in using both angular.copy and [].concact in your example is that it assigns a new reference of the array object to the lhs variable.

But consider the situation where you have array of objects.

  $scope.arr = [{name:'name1'}, {name:'name2'}, {name:'name3'}, {name:'name4'}];
  $scope.arrConcat = [].concat($scope.arr); //Get a new array
  $scope.arrCopy = angular.copy($scope.arr); //Get a new copy

 //Now change the name property of one of the item

  $scope.arr[3].name="Test";

 //Now see who all have been changed

 console.log($scope.arr[3].name); //Of course will output "Test"

 console.log($scope.arrConcat[3].name); //Will also output "Test" because the new array items still holds the same reference of the objects.

 console.log($scope.arrCopy[3].name); //Will output name4 because this contains another reference which holds the copy of the value of the object at index 3 from source array



//Push something on to the original array 
  $scope.arr.push({name:'name5'});

  //You will see that new item is not available here, which is exactly the behaviour that you are seeing in your case because both the arrConcat and arrCopy holds its own version of array through the items in arrConcat and arr are from the same reference.
  console.log($scope.arrConcat);
  console.log($scope.arrCopy);

So only thing is that in your case [].concat is kind of a convenient method to get a copy of the source array since your array just has primitives, so no issues.

Example - Demo

Upvotes: 2

user3991493
user3991493

Reputation:

http://plnkr.co/edit/06zLM8g34IDBLUmPtwV2?p=preview

var x = [5, 2];
var y = [].concat(x);
// y = [5, 2]


var x = [5, [5, 2]];
var y = [].concat(x);
// y = [5, 2]

Check this out, [].copy() never does a deep copy unlike angular.copy()

Upvotes: 0

Related Questions