How to insert an element at a specific index in an array with JavaScript

1 Answer

0 votes
let array = [4, 9, 8, 6, 5, 7];
let index = 2;
let newElement = 100;

// Insert the new element at the specified index
array.splice(index, 0, newElement);

console.log(array); 



/*
run:

[
  4, 9, 100, 8,
  6, 5,   7
]

*/

 



answered Feb 20, 2025 by avibootz

Related questions

...