JavaScript Code Exercises 2

JavaScript Code Exercises 2

Exercise 1: Reverse a string
Exercise 2: Factorialize a number
Exercise 3: Check for palindrome
Exercise 4: Find the longest word
Exercise 5: Title case a sentence
Exercise 6: Return largest numbers in arrays
Exercise 7: Confirm the ending
Exercise 8: Repeat a string
Exercise 9: Truncate a string
Exercise 10: Chunky monkey

Exercise 1: Reverse a string

Write a function that takes a string as input and returns the string reversed.

function reverseString(str) {

return str.split(“”).reverse().join(“”);

}

console.log(reverseString(“hello”)); // Output: “olleh”

In this example, we first split the string into an array of characters, then we reverse the array, and finally we join the reversed array back into a string.

Exercise 2: Factorialize a number

Write a function that takes a number as input and returns the factorial of that number.

javascript

Copy code

function factorialize(num) {

if (num === 0) {

return 1;

} else {

return num * factorialize(num – 1);

}

}

console.log(factorialize(5)); // Output: 120

In this example, we use recursion to calculate the factorial of a number. If the input number is 0, we return 1. Otherwise, we call the function again with num – 1 as input and multiply it with the current value of num.

Exercise 3: Check for palindrome

Write a function that takes a string as input and returns true if the string is a palindrome and false otherwise.

function isPalindrome(str) {

const reversedStr = str.split(“”).reverse().join(“”);

return str === reversedStr;

}

console.log(isPalindrome(“racecar”)); // Output: true

console.log(isPalindrome(“hello”)); // Output: false

In this example, we first reverse the input string and store it in a new variable called reversedStr. We then compare the original string to the reversed string and return true if they are equal.

Exercise 4: Find the longest word

Write a function that takes a string as input and returns the length of the longest word in the string.

function findLongestWord(str) {

const words = str.split(” “);

let longestWord = “”;

for (let word of words) {

if (word.length > longestWord.length) {

longestWord = word;

}

}

return longestWord.length;

}

console.log(findLongestWord(“The quick brown fox jumped over the lazy dog”)); // Output: 6

In this example, we first split the input string into an array of words. We then loop through each word and compare its length to the length of the current longest word. If the current word is longer, we update the value of longestWord. Finally, we return the length of the longest word.

Exercise 5: Title case a sentence

Write a function that takes a string as input and returns the string with the first letter of each word capitalized.

function titleCase(str) {

const words = str.toLowerCase().split(” “);

const titleCasedWords = [];

for (let word of words) {

titleCasedWords.push(word[0].toUpperCase() + word.slice(1));

}

return titleCasedWords.join(” “);

}

console.log(titleCase(“the quick brown fox”)); // Output: “The Quick Brown Fox”

In this example, we first convert the input string to lowercase and split it into an array of words. We then loop through each word, capitalize the first letter, and add it to a new array called titleCasedWords. Finally, we join the words in titleCasedWords back into a string and return it.

Exercise 6: Return largest numbers in arrays

Write a function that takes an array of arrays of numbers as input and returns an array containing the largest number from each array.

function largestNumbers(arr) {

const largest = [];

for (let subArr of arr) {

let max = subArr[0];

for (let num of subArr) {

if (num > max) {

max = num;

}

}

largest.push(max);

}

return largest;

}

console.log(largestNumbers([[1, 2, 3], [4, 5, 6], [7, 8, 9]])); // Output: [3, 6, 9]

In this example, we first create an empty array called largest. We then loop through each sub-array in the input array and find the largest number in that sub-array using another for loop. We update the value of max if we find a larger number. Finally, we add the largest number to the largest array and return it.

Exercise 7: Confirm the ending

Write a function that takes a string and a target substring as input and returns true if the string ends with the target substring, and false otherwise.

function confirmEnding(str, target) {

return str.slice(-target.length) === target;

}

console.log(confirmEnding(“hello world”, “world”)); // Output: true

console.log(confirmEnding(“hello world”, “goodbye”)); // Output: false

In this example, we use the slice() method to extract the substring of str that is the same length as target, starting from the end of the string. We then compare this extracted substring to the target substring and return true if they are equal.

Exercise 8: Repeat a string

Write a function that takes a string and a number as input and returns a new string that repeats the input string a given number of times.

function repeatString(str, num) {

let repeated = “”;

for (let i = 0; i < num; i++) {

repeated += str;

}

return repeated;

}

console.log(repeatString(“abc”, 3)); // Output: “abcabcabc”

In this example, we create an empty string called repeated. We then use a for loop to repeat the input string num times by adding it to the repeated string each iteration. Finally, we return the repeated string.

Exercise 9: Truncate a string

Write a function that takes a string and a number as input and returns a truncated version of the string, ending with an ellipsis (…) if the original string was longer than the given number.

function truncateString(str, num) {

if (str.length <= num) {

return str;

} else {

return str.slice(0, num) + “…”;

}

}

console.log(truncateString(“hello world”, 5)); // Output: “hello…”

In this example, we first check if the length of the input string is less than or equal to the given number. If it is, we simply return the original string. Otherwise, we use the slice() method to extract the first num characters of the string, and append an ellipsis to the end.

Exercise 10: Chunky monkey

Write a function that takes an array and a number as input and returns an array of arrays, where each sub-array contains a maximum of the given number of elements from the original array.

function chunkArray(arr, size) {

const chunks = [];

let i = 0;

while (i < arr.length) {

chunks.push(arr.slice(i, i + size));

i += size;

}

return chunks;

}

console.log(chunkArray([1, 2, 3, 4, 5], 2)); // Output: [[1, 2], [3, 4], [5]]

In this example, we create an empty array called chunks. We then use a while loop to iterate through the input array, taking slices of size elements at a time and pushing them to the chunks array. We use a separate variable i to keep track of our position in the input array. Finally, we return the chunks array.