Bhuneshwer Bhuneshwer - 1 year ago 85
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}]
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

Thanks in advance

Answer Source

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));
.as-console-wrapper { max-height: 100% !important; top: 0; }

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download