Q:

how to insert a value into an array javascript

// for me lol... pls don't delete!
// use splice to insert element
// arr.splice(index, numItemsToDelete, item); 
var list = ["hello", "world"]; 
list.splice( 1, 0, "bye"); 
//result
["hello", "bye", "world"]
5

var list = ["foo", "bar"];


list.push("baz");


["foo", "bar", "baz"] // result

3
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]
0

New to Communities?

Join the community