JS02 Exercises
Practical Exercises
- Write a function
arrayEquals(arr1, arr2)that compares two arrays elementwise.
function arrayEquals(arr1, arr2) {
if (arr1.length !== arr2.length) {
return false;
}
for (let i = 0; i < arr1.length; i++) {
if (arr1[i] !== arr2[i]) {
return false;
}
}
return true;
}- Write a function
removeByValue(arr, val)that removes an element from an array by its value.
function removeByValue(arr, val) {
return arr.filter(item => item !== val);
}- Write a function
removeByIndex(arr, idx)that removes an element from an array by its index.
function removeByIndex(arr, idx) {
if (idx < 0 || idx >= arr.length) {
return arr;
}
return arr.slice(0, idx).concat(arr.slice(idx + 1));
}- Write a function
min(arr)that returns the minimum of an array of numbers.
function min(arr) {
// solution 1
return Math.min(...arr);
// solution 2
let minValue = arr[0];
for (let i = 1; i < arr.length; i++) {
if (arr[i] < minValue) {
minValue = arr[i];
}
}
return minValue;
}- Write a function
max(arr)that returns the maximum of an array of numbers.
function max(arr) {
// solution 1
return Math.max(...arr);
// solution 2
let maxValue = arr[0];
for (let i = 1; i < arr.length; i++) {
if (arr[i] > maxValue) {
maxValue = arr[i];
}
}
return maxValue;
}- Write a function
mean(arr)that returns the mean of an array of numbers.
function mean(arr) {
let sum = 0;
for (let i = 0; i < arr.length; i++) {
sum += arr[i];
}
return sum / arr.length;
}- Write a function
median(arr)that returns the median of an array of numbers.
function median(arr) {
const sortedArray = arr.slice().sort((a, b) => a - b);
const midIndex = Math.floor(sortedArray.length / 2);
if (sortedArray.length % 2 === 0) {
// Average of two middle numbers for even-length array
return (sortedArray[midIndex - 1] + sortedArray[midIndex]) / 2;
} else {
// Middle number for odd-length array
return sortedArray[midIndex];
}
}- Write a function
mode(arr)that returns the mode of an array of numbers.
function mode(arr) {
let numCounts = {};
let maxCount = 0;
let modes = [];
// Count the occurrences of each number
arr.forEach(num => {
numCounts[num] = (numCounts[num] || 0) + 1;
if (numCounts[num] > maxCount) {
maxCount = numCounts[num];
}
});
// Find all numbers with the maximum count
for (let num in numCounts) {
if (numCounts[num] === maxCount) {
modes.push(Number(num));
}
}
return modes;
}- Write a function
range(start, stop, step)that returns an array containing the numbers from start to stop (including start but excluding stop) separated by the step step. For example,range(1, 10, 3)should return[1, 4, 7].
function range(start, stop, step) {
let result = [];
for (let i = start; i < stop; i += step) {
result.push(i);
}
return result;
}- Write a function
count(arr, elem)that returns the number of occurrences of elem in arr. For example,count(['a', 'b', 'a', 'b', 'c', 'a'], 'a')should return 3.
function count(arr, elem) {
let occurrence = 0;
for (let item of arr) {
if (item === elem) {
occurrence++;
}
}
return occurrence;
}- Write a function
sortStrings(arr)that takes an array of strings and returns a sorted array.
function sortStrings(arr) {
return arr.slice().sort();
// without sort
let sortedArray = arr.slice(); // Create a copy of the array
let length = sortedArray.length;
let swapped;
do {
swapped = false;
for (let i = 0; i < length - 1; i++) {
if (sortedArray[i] > sortedArray[i + 1]) {
// Swap elements
let temp = sortedArray[i];
sortedArray[i] = sortedArray[i + 1];
sortedArray[i + 1] = temp;
swapped = true;
}
}
} while (swapped);
return sortedArray;
}- Write a function
sortNumbers(arr)that takes an array of numbers and returns a sorted array. Definitely try outsortNumbers([1, 7, 12, 11, 23]). There is a high chance that your initial answer will return a wrong result (unless you carefully read the resources)!
function sortNumbers(arr) {
return arr.slice().sort((a, b) => a - b);
// without sort
let sortedArray = arr.slice(); // Create a copy of the array
for (let i = 1; i < sortedArray.length; i++) {
let current = sortedArray[i];
let j = i - 1;
while (j >= 0 && sortedArray[j] > current) {
sortedArray[j + 1] = sortedArray[j];
j--;
}
sortedArray[j + 1] = current;
}
return sortedArray;
}- Write a function
sortByAge(arr)that takes an array of objects where each object has the keys user and age and sorts them by age.
For example:
sortByAge([
{ user: "John Doe", age: 21 },
{ user: "Max Mustermann", age: 18 },
{ user: "Monika Musterfrau", age: 19 },
]);should return:
[
{ user: "Max Mustermann", age: 18 },
{ user: "Monika Musterfrau", age: 19 },
{ user: "John Doe", age: 21 },
];function sortByAge(arr) {
let sortedArray = arr.slice(); // Create a copy of the array
for (let i = 1; i < sortedArray.length; i++) {
let current = sortedArray[i];
let j = i - 1;
while (j >= 0 && sortedArray[j].age > current.age) {
sortedArray[j + 1] = sortedArray[j];
j--;
}
sortedArray[j + 1] = current;
}
return sortedArray;
}- Write a function
mergeAndSort(arr1, arr2)that merges two JavaScript arrays such that the result is sorted.
function mergeAndSort(arr1, arr2) {
return [...arr1, ...arr2].sort((a, b) => a - b);
// without using sort
let result = [];
let i = 0, j = 0;
while (i < arr1.length && j < arr2.length) {
if (arr1[i] < arr2[j]) {
result.push(arr1[i]);
i++;
} else {
result.push(arr2[j]);
j++;
}
}
// Append remaining elements (if any) from arr1
while (i < arr1.length) {
result.push(arr1[i]);
i++;
}
// Append remaining elements (if any) from arr2
while (j < arr2.length) {
result.push(arr2[j]);
j++;
}
return result;
}- Write a function
updateAge(user, age)that takes an object with keys firstName, lastName, address, email, and age and returns a new object that is the same as user except that the age has been replaced by age.
function updateAge(user, newAge) {
return {
...user,
age: newAge
};
}- Write a function
getRow(arr, i)that takes a two-dimensional JavaScript array and returns the ith row.
function getRow(arr, i) {
// Check if the row index is within the range of the array
if (i >= 0 && i < arr.length) {
return arr[i];
} else {
// Return an empty array or handle the error as preferred
return []; // or throw new Error('Row index out of bounds');
}
}- Write a function
getColumn(arr, j)that takes a two-dimensional JavaScript array and returns the jth row.
function getColumn(arr, j) {
let column = [];
for (let i = 0; i < arr.length; i++) {
if (arr[i] && arr[i][j] !== undefined) {
column.push(arr[i][j]);
} else {
// Handle the case where the column index is out of bounds
// or the row is shorter than the column index
// This can be an empty return or a specific error handling
// return []; // or throw new Error('Column index out of bounds');
}
}
return column;
}- Write a function
getSortedKeys(obj)that returns an array containing the sorted keys of the object.
function getSortedKeys(obj) {
return Object.keys(obj).sort();
}- Write a function
getSortedValues(obj)that returns an array containing the sorted values of the object.
function getSortedValues(obj) {
return Object.values(obj).sort((a, b) => {
if (typeof a === 'number' && typeof b === 'number') {
return a - b; // Numeric sorting
} else {
return a.toString().localeCompare(b.toString()); // String sorting for other types
}
});
}- Write a function
union(set1, set2)that finds the union of two sets.
function union(set1, set2) {
return new Set([...set1, ...set2]);
}- Write a function
intersection(set1, set2)that finds the intersection of two sets.
function intersection(set1, set2) {
let result = new Set();
for (let item of set1) {
if (set2.has(item)) {
result.add(item);
}
}
return result;
}- Write a function
removeDuplicates(arr)that returns arr with all duplicates removed.
function removeDuplicates(arr) {
return Array.from(new Set(arr));
}- Write a function
getScores(arr)that takes an array of pairs, where each pair contains the winner and the loser. The function should return a map containing each player together with the number of wins.
function getScores(arr) {
let scoresMap = new Map();
arr.forEach(([winner, loser]) => {
// Increment the win count for the winner
if (scoresMap.has(winner)) {
scoresMap.set(winner, scoresMap.get(winner) + 1);
} else {
scoresMap.set(winner, 1);
}
// Ensure the loser is also in the map (with 0 wins if not already present)
if (!scoresMap.has(loser)) {
scoresMap.set(loser, 0);
}
});
return scoresMap;
}- Write a function
addOneToMapKey(map, key)that takes a map and a key and adds one to the corresponding value if the key exists. If the key doesn’t exist, it should be added to the map with an initial value of 1.
function addOneToMapKey(map, key) {
if (map.has(key)) {
map.set(key, map.get(key) + 1);
} else {
map.set(key, 1);
}
}Theoretical Exercises
- Can you use the === operator to meaningfully compare two arrays for equality?
No, using the === operator to compare two arrays in JavaScript will only check if they reference the same object in memory, not if their contents are equal. To compare the contents of two arrays, you need to manually check each element for equality.
- Can you use the === operators to meaningfully compare two objects for equality?
No, the === operator in JavaScript only checks if two objects are the same
instance, not if they have equal contents.
- What are the differences between arrays and sets?
Arrays can contain duplicate elements and have an ordered sequence, whereas Sets automatically remove duplicates and do not maintain any specific order of elements. Arrays offer methods for indexing and manipulation, while Sets focus on uniqueness and efficient element existence checks.
- What are the differences between objects and maps? When would you use which?
Objects have string keys and inherit properties from their prototype, while Maps can have keys of any type and are iterable in insertion order. Use Objects for structured data with known, fixed keys, and Maps for dynamic collections with unique keys and frequent additions or deletions.
- Explain the mechanism of comparator functions that can be used for sorting an array.
Comparator functions for array sorting in JavaScript take two arguments and return a value indicating their relative order: negative if the first is less, positive if greater, zero if equal. This allows custom sorting logic beyond the default lexicographical order.
- What is the difference between a shallow copy and a deep copy?
A shallow copy of an object copies only the immediate properties, but not the nested objects; changes to nested objects in the original will affect the copy. A deep copy duplicates everything, including nested objects, ensuring full independence of the copy from the original.