Bhuneshwer Bhuneshwer - 24 days ago 11
Javascript Question

Insert array of object with in an objects array at specified position javascript

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 arr2 objects at 2nd position of arr1.

How to insert an array of object within an array of object at specified position like
Array.split()


Thanks in advance

Answer

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; }