splice coerces 2.5 to integer 2 (ToInteger(2.5) = 2). Inserts 50 at index 2, shifting 3,4,5 right: [1, 2, 50, 3, 4, 5].
Final Answer:
[1, 2, 50, 3, 4, 5] -> Option D
Quick Check:
Float index coerced to 2 [OK]
Hint: Always floor length/2 for middle index [OK]
Common Mistakes:
Confusing with unshift (insert at start)
Confusing with push (append at end)
Inserting at index 3 instead of 2
5. Given an array arr = [5, 10, 15, 20, 25], write a TypeScript function insertMiddle that inserts a given value exactly in the middle of the array. What will be the array after calling insertMiddle(arr, 12)?
hard
A. [5, 10, 12, 15, 20, 25]
B. [5, 10, 15, 12, 20, 25]
C. [12, 5, 10, 15, 20, 25]
D. [5, 10, 15, 20, 25, 12]
Solution
Step 1: Calculate middle index for odd length
arr.length = 5, middle index = Math.floor(5/2) = 2.
Step 2: Insert 12 at index 2
Using splice(2, 0, 12) inserts 12 before element at index 2 (which is 15), shifting elements right.
Final Answer:
[5, 10, 12, 15, 20, 25] -> Option A
Quick Check:
Inserted 12 at middle index 2 [OK]
Hint: Use Math.floor(length/2) for middle insertion [OK]
Common Mistakes:
Inserting at wrong index for odd length
Appending instead of inserting
Replacing element instead of inserting
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.