Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to sort the array in ascending order using the built-in method.
DSA Javascript
const numbers = [5, 3, 8, 1]; numbers.sort([1]); console.log(numbers);
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a function without parameters causes incorrect sorting.
Using (a, b) => b - a sorts in descending order, not ascending.
✗ Incorrect
The sort method requires a comparison function with two parameters a and b. Returning a - b sorts ascending.
2fill in blank
mediumComplete the code to find the median after sorting the array.
DSA Javascript
const arr = [7, 2, 5, 3]; arr.sort([1]); const mid = Math.floor(arr.length / 2); const median = arr.length % 2 !== 0 ? arr[mid] : (arr[mid - 1] + arr[mid]) / 2; console.log(median);
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Sorting descending changes the median calculation.
Not providing a comparison function sorts elements as strings.
✗ Incorrect
Sorting ascending with (a, b) => a - b is needed to find the correct median.
3fill in blank
hardFix the error in the code to correctly sort an array of strings by length.
DSA Javascript
const words = ['apple', 'dog', 'banana', 'cat']; words.sort((a, b) => [1]); console.log(words);
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a - b or b - a compares strings incorrectly.
Sorting descending when ascending is needed.
✗ Incorrect
To sort strings by length ascending, subtract b.length from a.length.
4fill in blank
hardFill both blanks to create a sorted array of unique numbers.
DSA Javascript
const nums = [4, 2, 5, 2, 3, 4]; const uniqueSorted = [...new Set(nums)].sort([1]); console.log(uniqueSorted);
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Not using a comparison function sorts numbers as strings.
Using arrow functions without parameters causes errors.
✗ Incorrect
Use (a, b) => a - b to sort numbers ascending after removing duplicates.
5fill in blank
hardFill all three blanks to create a sorted array of objects by age, then map to names.
DSA Javascript
const people = [
{ name: 'Alice', age: 30 },
{ name: 'Bob', age: 25 },
{ name: 'Carol', age: 35 }
];
const sortedNames = people.sort((a, b) => [1]).map(person => person.[2]).filter(name => name.length > [3]);
console.log(sortedNames); Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Sorting descending when ascending is needed.
Mapping to wrong property name.
Filtering with incorrect length value.
✗ Incorrect
Sort ascending by age with a.age - b.age, map to 'name', and filter names longer than 3 characters.