2

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

2
  • do you have the position? Commented Nov 13, 2016 at 14:29
  • Do you want to sort the final array? Commented Nov 13, 2016 at 14:31

4 Answers 4

4

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

Sign up to request clarification or add additional context in comments.

Comments

1

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)

Comments

1

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

1 Comment

concat will append the object at last position of array. I want objects to be added on specified position.
0

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.

1 Comment

Yes it does. Nina's answer shows as much. stackoverflow.com/a/40574963/3739551

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.