Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to remove the middle element from the array using splice.
DSA Javascript
const arr = [1, 2, 3, 4, 5]; const middleIndex = Math.floor(arr.length / 2); arr.splice([1], 1); console.log(arr);
Attempts:
3 left
💡 Hint
Common Mistakes
Using 0 as the start index removes the first element instead of the middle.
Using arr.length as the start index causes no removal because it's out of range.
✗ Incorrect
The splice method removes elements starting at the given index. To remove the middle element, we use middleIndex as the start.
2fill in blank
mediumComplete the code to remove the middle element from an array with even length.
DSA Javascript
const arr = [10, 20, 30, 40]; const middleIndex = arr.length / 2 - 1; arr.splice([1], 1); console.log(arr);
Attempts:
3 left
💡 Hint
Common Mistakes
Using length/2 as index removes the upper middle element instead of the lower.
Using 0 removes the first element.
✗ Incorrect
For even length arrays, the middle is often taken as the lower middle index, so we remove at middleIndex.
3fill in blank
hardFix the error in the code to correctly remove the middle element from the array.
DSA Javascript
const arr = [5, 6, 7, 8, 9]; const middleIndex = Math.floor(arr.length / 2); arr.splice([1], 1); console.log(arr);
Attempts:
3 left
💡 Hint
Common Mistakes
Using arr.length as index causes no removal.
Using 0 removes the first element.
✗ Incorrect
The splice method needs the start index to remove the middle element, which is middleIndex.
4fill in blank
hardFill both blanks to remove the middle element and print the updated array length.
DSA Javascript
const arr = [2, 4, 6, 8, 10, 12]; const middleIndex = [1]; arr.splice(middleIndex, [2]); console.log(arr.length);
Attempts:
3 left
💡 Hint
Common Mistakes
Removing two elements instead of one.
Using wrong middle index for even length.
✗ Incorrect
For even length arrays, middleIndex is length/2 - 1. We remove one element at that index.
5fill in blank
hardFill all three blanks to remove the middle element and return the updated array.
DSA Javascript
function removeMiddle(arr) {
const middleIndex = [1];
arr.splice(middleIndex, [2]);
return [3];
}
console.log(removeMiddle([7, 8, 9, 10, 11]));Attempts:
3 left
💡 Hint
Common Mistakes
Returning arr.length instead of the array.
Removing more than one element.
✗ Incorrect
Calculate middleIndex as floor of length/2, remove one element, then return the updated array.
