how to add new index in array in typescript 1

how to add new index in array in typescript

const items = [1, 2, 3, 4, 5]

const insert = (arr, index, newItem) => [
  // part of the array before the specified index
  ...arr.slice(0, index),
  // inserted item
  newItem,
  // part of the array after the specified index
  ...arr.slice(index)
]

const result = insert(items, 1, 10)

console.log(result)
// [1, 10, 2, 3, 4, 5]
 Run code snippetHide results

Here is what the above code is Doing:
1. We have an array of items.
2. We have a function that takes an array, an index, and a new item.
3. The function returns a new array with the new item inserted at the specified index.
4. We call the function with the items array, an index of 1, and a new item of 10.
5. The function returns a new array with the new item inserted at the specified index.

The function is pure because it doesn’t modify the original array. It returns a new array with the new item inserted.

The function is also referentially transparent because it always returns the same result for the same arguments.

The function is also composable because we can use it in other functions.

Similar Posts