0

I am trying to implement a logic that, i want to push some objects into the array after a specic index like, In a array have 5 objects then , i want to push two new objects after 3 index in current array. How can i do it.

const currarr = [{id:1,name:"abc"},{id:2,name:"efg"},{id:3,name:"hij"},{id:4,name:"klm"},{id:5,name:"nop"}];

otherObj = [{id:6,name:"fdf"},{id:7,name:"gfg"}]

I want to push the two new objects of otherObj array into the currarr array after the 3 index.

vjtechno
  • 452
  • 1
  • 6
  • 16
  • 1
    use `Array.prototype.splice` for that – Alan Omar Jun 26 '22 at 11:17
  • Take a look at here: https://stackoverflow.com/questions/586182/how-to-insert-an-item-into-an-array-at-a-specific-index-javascript – ihsany Jun 26 '22 at 11:19
  • Does this answer your question? [How to insert an item into an array at a specific index (JavaScript)](https://stackoverflow.com/questions/586182/how-to-insert-an-item-into-an-array-at-a-specific-index-javascript) – Alan Omar Jun 26 '22 at 11:28

3 Answers3

1
curarr.splice(3, 0, ...otherObj)
0

With the splice method, you can add or delete elements from a specific index.

For more resources.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice

const currarr = [{id:1,name:"abc"},{id:2,name:"efg"},{id:3,name:"hij"},{id:4,name:"klm"},{id:5,name:"nop"}];

const otherObj = [{id:6,name:"fdf"},{id:7,name:"gfg"}]


currarr.splice(3, 0, ...otherObj)

console.log(currarr)
Mina
  • 14,386
  • 3
  • 13
  • 26
0

The slice() method returns a shallow copy of a portion of an array into a new array object selected from start to end (end not included) where start and end represent the index of items in that array. The original array will not be modified.

for more checkout below links Mozila W3c

Sam
  • 29
  • 5