Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to reverse the array using the built-in method.
DSA Javascript
const arr = [1, 2, 3, 4, 5]; arr.[1](); console.log(arr);
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'sort' instead of 'reverse' changes order but not necessarily reverses.
Using 'splice' or 'push' does not reverse the array.
✗ Incorrect
The built-in method to reverse an array in JavaScript is 'reverse()'.
2fill in blank
mediumComplete the code to reverse the array by swapping elements using a for loop.
DSA Javascript
const arr = [10, 20, 30, 40, 50]; for(let i = 0; i < arr.length / 2; i++) { let temp = arr[i]; arr[i] = arr[arr.length - 1 - [1]]; arr[arr.length - 1 - i] = temp; } console.log(arr);
Attempts:
3 left
💡 Hint
Common Mistakes
Using a fixed number instead of 'i' causes incorrect swapping.
Using 'temp' or '0' in the index is incorrect.
✗ Incorrect
To swap elements from start and end, use the current index 'i' to find the matching element from the end.
3fill in blank
hardFix the error in the recursive function to reverse an array.
DSA Javascript
function reverseArray(arr) {
if(arr.length === 0) return [];
return [arr.pop()][1] reverseArray(arr);
}
const result = reverseArray([1, 2, 3]);
console.log(result);Attempts:
3 left
💡 Hint
Common Mistakes
Using '+' causes arrays to convert to strings.
Using ',' or '-' is invalid syntax here.
✗ Incorrect
To combine arrays in JavaScript, use 'concat' method instead of '+' operator.
4fill in blank
hardFill both blanks to create a new reversed array using map and length.
DSA Javascript
const arr = [5, 10, 15, 20]; const reversed = arr.map((_, [1]) => arr[[2] - 1 - [1]]); console.log(reversed);
Attempts:
3 left
💡 Hint
Common Mistakes
Using '_' as index causes errors.
Using 'length' alone is undefined.
Using 'index' without declaration.
✗ Incorrect
In map, the second parameter is the index, here named 'i'. The array length is accessed by 'arr.length'.
5fill in blank
hardFill all three blanks to reverse an array using reduce.
DSA Javascript
const arr = [2, 4, 6, 8]; const reversed = arr.reduce(([1], [2]) => [[2], ...[1]], []); console.log(reversed);
Attempts:
3 left
💡 Hint
Common Mistakes
Swapping accumulator and current causes wrong results.
Not using spread operator causes nested arrays.
✗ Incorrect
In reduce, 'acc' is accumulator and 'curr' is current element. We prepend 'curr' to 'acc' to reverse.
