Reputation: 1329
I have two object arrays that have similar values but I cannot figure out how to merge them.
var Cars = [{
lat: 42,
lng: -72
}, {
lat: 40.7127837,
lng: -74.0059413
}, {
lat: 40.735657,
lng: -74.1723667
}];
var Trucks = [{
lat: 43,
lng: -72.5
}, {
lat: 40.612837,
lng: -74.1239413
}, {
lat: 40.564657,
lng: -74.1803667
}];
I have tried the code below but all I get in the console is a bunch of objects no values.
var Vehicles = Cars.concat(Trucks);
for (var i = 0; i < Vehicles.length; i++)
{
console.log(Vehicles[i]);
}
Upvotes: 0
Views: 81
Reputation: 12136
Array.prototype.push.apply(Cars, Trucks)
EDIT: Explanation
Both Cars
and Trucks
are array
s. The push
function on the Array
prototype receives as many parameters as you want and pushes each of them into an array. For example:
var a = [1,2];
a.push(3,4,5);
console.log(a); // => [1,2,3,4,5]
When calling apply
on any function, you specify two things: the value of the this
variable within the function, and an array containing the list of parameters being passed on the function. Therefore calling
Array.prototype.push.apply(a, [3,4,5])
will call the push
function on the a
array, by passing it three parameters: 3
, 4
and 5
.
EDIT 2: Please note that doing this will overwrite the original array (the one being pass as the first parameter to the apply
function call).
Upvotes: 1