0

I have 2 arrays,

$scope.first = [
  { fName:'Alex', lName='Doe' },
  { fName:'John', lName='S' }
]

var second= [
  { fName:'Tom', lName='M', email:'tom@gmail.com' },
  { fName:'Jerry', lName='L', email:'jerry@gmail.com' }
]

I need to push second array into first array and want to result like:

$scope.first = [
  { fName:'Alex', lName='Doe' },
  { fName:'John', lName='S' },
  { fName:'Tom', lName='M', email:'tom@gmail.com' },
  { fName:'Jerry', lName='L', email:'jerry@gmail.com' }
]
om_jaipur
  • 2,176
  • 4
  • 30
  • 54

3 Answers3

2

If you want to push elements from one array into an existing array you can do

[].push.apply($scope.first, second);

If you want to create a new array that contains elements of both arrays, use concat:

$scope.first = $scope.first.concat(second);
hansmaad
  • 18,417
  • 9
  • 53
  • 94
  • 1
    `[].push.apply()` what you mean by `[ ]`, first array(`$scope.first`)? – om_jaipur Aug 25 '17 at 12:19
  • `[]` is an array :) You could also write `Array.prototype.push.apply(...)` or `$scope.first.push.apply(...)` or `second.push.apply(...)`. It doesn't matter. It#s just a way to reference the push method. – hansmaad Aug 25 '17 at 12:21
  • `[]` in js represents an array. Read more here - https://stackoverflow.com/questions/33514915/what-s-the-difference-between-and-while-declaring-a-javascript-array – abhig10 Aug 25 '17 at 12:23
0

I would try $scope.first.concat($scope.second)

Lehlohonolo
  • 116
  • 1
  • 7
0
$scope.first = [
  { fName:'Alex', lName='Doe' },
  { fName:'John', lName='S' }
]

var second= [
  { fName:'Tom', lName='M', email:'tom@gmail.com' },
  { fName:'Jerry', lName='L', email:'jerry@gmail.com' }
]

$scope.first = $scope.first.concat(second)