user2851669
user2851669

Reputation:

concatenation of two arrays

I have an array:

$scope.array2 = ["3","4","5"];
$scope.array = [["1"],["2"],["3"]];
$scope.array[0].concat(array2);

Expected output:

$scope.array = [["1","3","4","5"],["2"],["3"]];

But the array is unchanged after concat. How can I solve this problem?

Upvotes: 0

Views: 117

Answers (5)

Cerbrus
Cerbrus

Reputation: 72837

To get the desired result, you'd have to do something like this:

$scope.array2 = ["3","4","5"];
$scope.array = [["1"],["2"],["3"]];
$scope.array[0] = $scope.array[0].concat($scope.array2);

Array.prototype.concat actually returns the result, instead of modifying it's subject.
You'll have to save the result of the contact to $scope.array[0].


Also, have a look at @Phil's answer, using push, that also returns the desired result, without having to assign the result separately.

Upvotes: 4

Phil
Phil

Reputation: 164731

You can use Array.prototype.push to merge the the second array into the first which does mutate the original array as desired. Try

Array.prototype.push.apply($scope.array[0], $scope.array2)

Originally referenced here ~ Example: Merging two arrays

var array2 = ["3","4","5"],
    array = [["1"],["2"],["3"]];

document.getElementById('array').innerHTML = 'array = ' + JSON.stringify(array);
document.getElementById('array2').innerHTML = 'array2 = ' + JSON.stringify(array2);

Array.prototype.push.apply(array[0], array2);
document.getElementById('zomg').innerHTML = 'ZOMG! ' + JSON.stringify(array);
<pre id="array"></pre>
<pre id="array2"></pre>
<pre id="zomg"></pre>

Upvotes: 2

Robin-Hoodie
Robin-Hoodie

Reputation: 4974

The concat function returns a new array that is concatenated and leaves the original arrays unchanged.

Try :

    $scope.array2 = ["3","4","5"];
    $scope.array = [["1"],["2"],["3"]];
    $scope.array[0] = $scope.array[0].concat($scope.array2);

Upvotes: 1

jensgram
jensgram

Reputation: 31508

As Array.concat() returns a new array, you must reassign the return value:

$scope.array[0] = $scope.array[0].concat(array2);

Upvotes: 1

xdazz
xdazz

Reputation: 160833

concat doesn't change the original array, you should do like below:

  $scope.array[0] = $scope.array[0].concat(array2);

Upvotes: 1

Related Questions