I am looking for a JavaScript array insert method, in the style of:
arr.insert(index, item)

I'm in need for multiple alternative approaches.

I wanted to place a known number of items into an array, into specific positions, as they come off of an "associative array" (i.e. an object) which by definition is not guaranteed to be in a sorted order. I wanted the resulting array to be an array of objects, but the objects to be in a specific order in the array since an array guarantees their order.

ram-kasarla
Ram KasarlaDec 24, 2022, 03:41 AM

Replies

Answers

Loginand verify email to answer
0

You can use splice() for this

The splice() method usually receives three arguments when adding an

  1. The index of the array where the item is going to be added.
  2. The number of items to be removed, which in this case is 0.
  3. The element to add.
let array = ['item 1', 'item 2', 'item 3']
let insertAtIndex = 0
let itemsToRemove = 0
    
array.splice(insertAtIndex, itemsToRemove, 'insert this string on index 0')

console.log(array)
revanth-k
Revanth KDec 24, 2022, 03:43 AM

Replies