16 Practice Problems to Test and Reinforce JavaScript Fundamentals
A computer algorithm is a sequence of steps that is followed to achieve a particular outcome. To write an algorithm, you must first understand a problem, and then solve it with coding.
To make solving problems easier, it can be helpful to break them down into many chunks. Then, each chunk can be solved one by one. For example, if you are building a calculator, don't try to solve the problem as a whole. First, consider how to get inputs. Then, determine each arithmetic operation one by one. Finally, display the results.
In this section we will learn to solve basic algorithm problems using JavaScript. This will help you improve your problem solving skills and prepare you to later solve more complex problems.
Hint: If you get stuck, try using console.log() to log variable values to the console. This will help to debug problems.
1. Convert from Celsius to Fahrenheit
function convertToF(celsius) {
// Only change code below this line
var fahrenheit = celsius * (9 / 5) + 32;
// Only change code above this line
if (typeof fahrenheit !== "undefined") {
return fahrenheit;
} else {
return "fahrenheit not defined";
}
}
// Change the inputs below to test your code
convertToF(30);
Code Explanation
- Declare the fahrenheit variable.
- Make sure the proper order of arithmetic operations is followed by using parenthesis (()) when needed.
2. Reverse the provided string.
function reverseString(str) {
return str
.split("")
.reverse()
.join("");
}
Code Explanation
- Declare the fahrenheit variable.
- Make sure the proper order of arithmetic operations is followed by using parenthesis (()) when needed.
3. Find the factorial
function factorialize(num) {
if (num === 0) {
return 1;
}
return num * factorialize(num - 1);
}
factorialize(5);
Code Explanation
- Notice at the first line we have the terminal condition, i.e a condition to check the end of the recursion. If num == 0, then we return 1, i.e. effectively ending the recursion and informing the stack to propagate this value to the upper levels. If we do not have this condition, the recursion would go on until the stack space gets consumed, thereby resulting in a Stack Overflow.
4. Find the Longest Word in a String
function findLongestWordLength(str) {
return Math.max(...str.split(" ").map(word => word.length));
}
Code Explanation
- We provide Math.max with the length of each word as argument, and it will simply return the highest of all.
- Let’s analyze everything inside the Math.max parenthesees to understand how we do that.
- str.split(" ") splits the string into an array, taking spaces as separators. It returns this array: [“The”,"quick,“brown”,“fox”,“jumped”,“over”,“the”,“lazy”,“dog”].
- Then, we will make another array, made from the lengths of each element of the str.split(" ") array with map(). str.split(" ").map(word => word.length) returns [3, 5, 5, 3, 6, 4, 3, 4, 3]
- Finally, we pass the array as argument for the Math.max function with the spread operator ...
5. Find the Largest Numbers in Arrays
function largestOfFour(arr) {
return arr.map(function(group) {
return group.reduce(function(prev, current) {
return current > prev ? current : prev;
});
});
}
Code Explanation
- We map all items within the main array to a new array using Array.prototype.map() and return this array as the final result.
- Within each inner array, we reduce its contents down to a single value using Array.prototype.reduce()
- The callback function passed to the reduce method takes the previous value and the current value and compares the two values.
- If the current value is higher than the previous value we set it as the new previous value for comparison with the next item within the array or returns it to the map method callback if it’s the last item.
6. Check if a string ends with the given target string.
function confirmEnding(str, target) {
return str.slice(-target.length) === target
}
confirmEnding("Bastian", "n");
Code Explanation
- If a negative number is provided as the first parameter to slice() , the offset is taken backwards from the end of the string
7. Repeat a given string str N times.
function repeatStringNumTimes(str, num) {
if (num < 1) {
return ""; //return blank string if input is negative.
} else if (num === 1) {
return str;
} else {
return str + repeatStringNumTimes(str, num - 1);
}
}
Code Explanation
- This solution uses recursion.
- We check if num is negative and return an empty string if true.
- Then we check if it’s equal to 1 and in that case we return the string itself.
- If not, we add the string to a call of our function with num being decreased by 1, which will add another str and another… until eventually num is 1. And return that whole process.
8. Truncate a string if it is longer than the given maximum string length and return it ending with ...
function truncateString(str, num) {
// Clear out that junk in your trunk
if (str.length > num) {
return str.slice(0, num) + "...";
} else {
return str;
}
}
Code Explanation
- We start off with a simple if statement to determine one of two outcomes…
- If our string length is greater than the num we want to truncate it, we return a slice of our string starting at character 0, and ending at num. We then append our '...' to the end of the string.
- However, if above situation is not true, it means our string length is less than our truncation num. Therefore, we can just return the string.
9. Check if a value is classified as a boolean primitive.
function booWho(bool) {
return typeof bool === "boolean";
}
booWho(null);
Code Explanation
- Uses the operator typeof to check if the variable is a boolean. If it is, it will return true. Otherwise, if it is any other type it will return false.
10. Finders Keepers
Create a function that looks through an array arr and returns the first element in it that passes a 'truth test'. This means that given an element x, the 'truth test' is passed if func(x) is true. If no element passes the test, return undefined.
function findElement(arr, func) {
let num = 0;
for (var i = 0; i < arr.length; i++) {
num = arr[i];
if (func(num)) {
return num;
}
}
return undefined;
}
Code Explanation
- Challenge asks us to look through array. This is done using a for loop.
- The num variable is being passed into the function, so we set it to each index in our array.
- The pre-defined function already checks each number for us, so if it is “true”, we return that num.
- If none of the numbers in the array pass the function’s test, we return undefined.
11. Title Case a Sentence
Return the provided string with the first letter of each word capitalized. Make sure the rest of the word is in lower case.
function titleCase(str) {
var convertToArray = str.toLowerCase().split(" ");
var result = convertToArray.map(function(val) {
return val.replace(val.charAt(0), val.charAt(0).toUpperCase());
});
return result.join(" ");
}
titleCase("I'm a little tea pot");
Code Explanation
- We are making entire string lowercase and then converting it into array. Then we are using map function to replace the lowercase character with uppercase. Finally, we are returning the string using join method.
12. Slice and Splice
You are given two arrays and an index. Copy each element of the first array into the second array, in order. Begin inserting elements at index n of the second array. Return the resulting array. The input arrays should remain the same after the function runs.
function frankenSplice(arr1, arr2, n) {
// It's alive. It's alive!
let localArr = arr2.slice();
localArr.splice(n, 0, ...arr1);
return localArr;
}
Code Explanation
- Since our goal is to return the new array with out altering arr1 or arr2 we create a localArr and add all the items from arr2 using the slice() function
- Since the splice() function will mutate (alter) arrays and can be used to add new elements we will use it to add the contents of arr1 into localArr. n is the starting position where our content will be inserted. We won’t be deleting any elements so the next argument is 0. Then we add the entire contents of arr1 using spread syntax ....
13. Falsy Bouncer
Remove all falsy values from an array. Falsy values in JavaScript are false, null, 0, "", undefined, and NaN. Hint: Try converting each value to a Boolean.
function bouncer(arr) {
let newArray = [];
for (var i = 0; i < arr.length; i++) {
if (arr[i]) newArray.push(arr[i]);
}
return newArray;
}
Code Explanation
- We create a new empty array.
- We use a for cycle to iterate over all elements of the provided array (arr).
- We use the if statement to check if the current element is truthy 1.5k or falsy 1.7k.
- If the element is truthy, we push it to the new array (newArray). This result in the new array (newArray) containin>- only truthy elements.
- We return the new array (newArray).
14. Where do I Belong
Return the lowest index at which a value (second argument) should be inserted into an array (first argument) once it has been sorted. The returned value should be a number.
function getIndexToIns(arr, num) {
arr.push(num);
arr.sort(function(a, b) {
return a - b;
});
return arr.indexOf(num);
}
Code Explanation
- First we add the number num to the array using push() which adds it as the last element of the array.
- Then we use sort() with the callback function function(a, b){return a-b} to sort the numbers in ascending order.
- Lastly we return the postion or index of num in the array with the indexOf() function.
15. Mutations
Return true if the string in the first element of the array contains all of the letters of the string in the second element of the array.
function mutation(arr) {
return arr[1]
.toLowerCase()
.split("")
.every(function(letter) {
return arr[0].toLowerCase().indexOf(letter) != -1;
});
}
Code Explanation
Grab the second string, lowercase and turn it into an array; then make sure every one of its letters is a part of the lowercased first string.
Every will basically give you letter by letter to compare, which we do by using indexOf on the first string. indexOf will give you -1 if the current letter is missing. We check that not to be the case, for if this happens even once every will be false.
16. Chunky Monkey
Write a function that splits an array (first argument) into groups the length of size (second argument) and returns them as a two-dimensional array.
function chunkArrayInGroups(arr, size) {
// Break it up.
var arr2 = [];
for (var i = 0; i < arr.length; i += size) {
arr2.push(arr.slice(i, i + size));
}
return arr2;
}
Code Explanation
- First, we create an empty array arr2 where we will store our ‘chunks’.
- The for loop starts at zero, increments by size each time through the loop, and stops when it reaches arr.length.
- Note that this for loop does not loop through arr. Instead, we are using the loop to generate numbers we can use a> indices to slice the array in the right locations.
- Inside our loop, we create each chunk using arr.slice(i, i+size), and add this value to arr2 with arr2.push().
- Finally, we return the value of arr2.
If you learned something interesting from this article, please follow this blog and drop a like. Also, comments are appreciated. Thank you for dropping by!