OneCompiler

[JavaScript] How to insert an element in the middle of the array?

I want to insert a new element in the middle of an array, how to do that in Javascript?

1 Answer

4 years ago by

You can use splice() function to add elements to an array in Javascript.

let numbers = [1,2,3,4,6,7,8,9];
let middleIndex = Math.round((numbers.length - 1) / 2);
numbers.splice(middleIndex, 0, 5); //Syntax: array.splice(index, howmany items to be removed, item1, ....., itemn)

Try checking the result here:https://onecompiler.com/javascript/3xmt992ux

4 years ago by Meera