Reputation: 587
I have two array of objects say var arr1 = [{a:12},{d:14}]
and var arr2 = [{b:15},{c:10}]
, I want the following result : arr3 = [{a:12},{b:15},{c:10},{d:14}]
I want to add objects in arr2 at position 2 of arr1. Note the order of a,b,c,d in arr3.
How to insert an array of objects within another array of objects at specified position like Array.split()
Thanks in advance
Upvotes: 2
Views: 1361
Reputation: 115222
Use Array#splice
method with Function#apply
method.
var arr1 = [{
a: 12
}, {
d: 14
}],
arr2 = [{
b: 15
}, {
c: 10
}];
// copy array
var arr3 = arr1.slice();
// insert elements into the array
// with spread operator
[].splice.apply(arr3, [1, 0, ...arr2]); // where first element in array is the insert position
// or with concat method
// [].splice.apply(arr3, [1, 0].concat(arr2));
console.log(arr3);
Upvotes: 1
Reputation: 386570
You could use Array#splice
with Function#apply
for it.
This allows to insert an array into a given array at a certain position.
var arr1 = [{ a: 12 }, { d: 14 }],
arr2 = [{ b: 15 }, { c: 10 }];
Array.prototype.splice.apply(arr1, [1, 0].concat(arr2));
console.log(arr1);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Upvotes: 4
Reputation: 122047
You could use splice()
with ...
spread operator.
var arr1 = [{a:12},{d:14}]
var arr2 = [{b:15},{c:10}]
arr1.splice(1, 0, ...arr2);
console.log(arr1)
If you want to keep original array you can first create copy using slice()
var arr1 = [{a:12},{d:14}]
var arr2 = [{b:15},{c:10}]
var result = arr1.slice(0);
result.splice(1, 0, ...arr2);
console.log(result)
Upvotes: 1
Reputation: 2257
As long as you know the position, it sounds like you want array.splice()
.
var myFish = ["angel", "clown", "mandarin", "surgeon"];
myFish.splice(2, 0, "drum");
Example taken from:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice
You can do the exact same thing with objects.
Upvotes: 0