In this tutorial I’m going to show you how you can insert a list of items at a particular index (and the following indices) in another array. If you want to know how to insert a single object, you can follow the previous article.
For instance, if I have an array of elements [1,2,3,4,5]. I want to insert [22,33] in the array so that the resultant array would look like [1,2,22,33,3,4,5]. Given, I already know that I want to begin appending the items after the 3rd position.
I’ve demonstrated the same but with array of objects with the following example. Here, I’ve split the original array and then merged all the three arrays in the required sequence.
const firstList = [
{ id: 1, name: 'Gautam' },
{ id: 2, name: 'Rob' },
{ id: 3, name: 'Tina' },
{ id: 4, name: 'Martin' },
{ id: 5, name: 'Julia' },
{ id: 6, name: 'Emma' },
]
const newList = [
{ id: 33, name: 'Joseph' },
{ id: 44, name: 'David' },
{ id: 55, name: 'Hannah' },
]
const insertPosition = 3
const segment1 = firstList.splice(0, insertPosition)
const segment2 = firstList
const appendedList = [...segment1, ...newList, ...segment2]
console.log(appendedList)
Code language: JavaScript (javascript)
The resultant output of the above code should look like:
[
{ id: 1, name: 'Gautam' },
{ id: 2, name: 'Rob' },
{ id: 3, name: 'Tina' },
{ id: 33, name: 'Joseph' },
{ id: 44, name: 'David' },
{ id: 55, name: 'Hannah' },
{ id: 4, name: 'Martin' },
{ id: 5, name: 'Julia' },
{ id: 6, name: 'Emma' }
]
Code language: JavaScript (javascript)
If you have any doubts or suggestions, let me know in the comments below!