const arr = [10, 20, 30, 40, 50]; const middleIndex = Math.floor(arr.length / 2); arr.splice(middleIndex, 0, 99); console.log(arr);
The array length is 5, so middleIndex = Math.floor(5 / 2) = 2.
Using splice at index 2 inserts 99 before the element originally at index 2.
Resulting array: [10, 20, 99, 30, 40, 50]
const arr = [1, 2, 3, 4]; const mid = Math.floor(arr.length / 2); arr.splice(mid, 0, 99, 100); console.log(arr);
Array length is 4, so mid = 2.
Splice inserts 99 and 100 at index 2, pushing elements 3 and 4 to the right.
Final array: [1, 2, 99, 100, 3, 4]
const arr = [5, 10, 15, 20, 25]; const mid = arr.length / 2; arr.splice(mid, 0, 42); console.log(arr);
arr.length / 2 is 2.5, a float.
splice expects an integer index, so 2.5 is converted to 2 internally, but this can cause confusion or unexpected results.
Using Math.floor(arr.length / 2) ensures an integer index.
Inserting in the middle requires shifting all elements after the insertion point one position to the right.
This shifting takes linear time proportional to the number of elements after the insertion point.
const arr: number[] = [];
function insertMiddle(val: number) {
const mid = Math.floor(arr.length / 2);
arr.splice(mid, 0, val);
}
insertMiddle(1);
insertMiddle(2);
insertMiddle(3);
insertMiddle(4);
console.log(arr);Step 1: Insert 1 at middle of [] → [1]
Step 2: Insert 2 at middle of [1] (index 0) → [2, 1]
Step 3: Insert 3 at middle of [2, 1] (index 1) → [2, 3, 1]
Step 4: Insert 4 at middle of [2, 3, 1] (index 1) → [2, 4, 3, 1]
