Complete the code to insert an element at the middle index of the array.
const arr = [1, 2, 4, 5]; const middle = Math.floor(arr.length / 2); arr.splice([1], 0, 3); console.log(arr);
The splice method inserts elements at the specified index. Using middle inserts the element at the middle of the array.
Complete the code to find the middle index correctly for an odd-length array.
const arr = [10, 20, 30, 40, 50]; const middle = [1]; console.log(middle);
Math.ceil which gives an index beyond the middle.arr.length - 1 which is the last index.Using Math.floor(arr.length / 2) gives the correct middle index for odd-length arrays.
Fix the error in the code to insert element 99 at the middle index.
const arr = [5, 10, 15, 20]; const mid = Math.floor(arr.length / 2); arr.splice(mid, [1], 99); console.log(arr);
The second argument to splice is the number of elements to remove. To insert without removing, use 0.
Fill both blanks to insert element 7 at the middle index without removing any elements.
const arr = [2, 4, 6, 8]; const mid = [1]; arr.splice(mid, [2], 7); console.log(arr);
Calculate the middle index with Math.floor(arr.length / 2) and set delete count to 0 to insert without removing.
Fill all three blanks to insert element 100 at the middle index of the array.
const arr = [10, 20, 30, 40, 50, 60]; const mid = [1]; arr.splice(mid, [2], [3]); console.log(arr);
Calculate middle index with Math.floor(arr.length / 2), delete 0 elements, and insert 100.
