Solving Five FreeCodeCamp Javascript problems

Yeah, I managed to solve 5 more FCC JS problems in one day (I spent all day, don't think I'm some sort of Javascript guru, not at all) around a week or so ago, I'm posting this today because even though I wanted to post about this over the past month, I haven't had much time (not because I've been too busy, but because most of my leisure time is used to learn Javascript) to post.

I already finished 15 problems an hopefully I'll finish the 20 problems before this friday, and hopefully I'll post them, but in the meantime, I'll leave my usual timetable of "learning to program" so you see my progress:

ConceptTime spent
Researching Howto8 hours
Downloading programs2 hours
Learning Javascript43 hours (so far)

I already know the basics, so the next five problems were hard but not impossible!

image.png

These challenges set some ground rules and they ask you to achieve something by writing your own code. I solved from problem 3 to 8 ,and it looks like this:

Heads up, I'm not using any type of coding format because everything below this line is mostly code, so I'll stick with normal Hive format right now. I am copying and pasting from my Visual Studio files where I keep comments, code, notes and whatnot, hopefully you get what I meant while writing it and at the same time, you understand all my giberish.

Find Longest Word

function findLongestWord(str) {
// Before we return the length of the longest word, we first have to find out what is the longest word.
// Right now we have the sentence in a string format, now we need a way to separate those words individually, so...
var words = str.split(" "); // This is the delimitor which we'll use to separate the words, wherever there's a space, the code will split those into separate strings in an array.
console.log(words);
}

findLongestWord("The big blue waves smashed over the shiny coast");

/*
This code would output will output as follows:
'The'
'big'
'blue'
'waves'
'smashed'
'over'
'the'
'shiny'
'coast'

//*********************************************/

// And we can loop over that array with a regular loop like this one:

var regards = ['hola', 'hello', 'konichiwa']
for (var i=0; i<regards.length; i++){
console.log (regards[i])
}

// OR we could loop through the array with:

var regards = ['hola', 'hello', 'konichiwa']
for (var regard of regards) {
console.log(regard) // This way we can loop through regards in a much simpler way
} // Now we don't have to deal with the indexes. This loop goes over the elements, whereas the other loop goes over the indexes.

function findLongestWord(str) {
var words = str.split(" ");
for (var word of words) {
console.log(word);
}
}

// findLongestWord("The big blue waves smashed over the shiny coast");

// Now we need to find the longest word by creating a variable:

function findLongestWord(str) {
var words = str.split(" ");
var longest = ""; // We are going to store the longest word in this variable.

 for (var word of words) {
     // While we are looking through each element (or word) we need to check how long the word is with the "if" as follows:
     if (word.length > longest.length) longest = word;      // If the length of the current word is longest than "longest word.length"
 }
 return longest;

}

console.log(findLongestWord("The big blue waves smashed over the shiny coast")); // Remember that I use console.log because Visual Studio needs to return something even though there's no function (return is for functions).

// So the logic of the code goes: The first loop is going to be "the" and then we go... is "the.lenght" (which is three) greater than zero? Yes, so the longest word is "the; then the second loop which is "big" checks if "big.length" is longer than "the.length" which is currently the longest word; then the loop goes through "blue.length" and checks if its longer than "the.length", yes, so the longes word is "blue"... and so on, checks every word against the previous longest word, giving us the longest word of the array.

//***************************************/

// We already have the longest word; since we already have the longest one, we can just add ".length" after longest and we are done.

function findLongestWord(str) {
var words = str.split(" ");
var longest = "";

for (var word of words) {
    if (word.length > longest.length) longest = word;
}
return longest.length;

}

console.log(findLongestWord("The big blue waves smashed over the shiny coast"));

// Now that we know the logic behind this code, we can actually do it in one line as follows:

function findLongestWord(str) {
return str.split(" ").sort(function(a, b) {return b.length - a.length}); // The we can just ask for the first one with ... - a.length)}[0]; because the index 0 is the longest one and we'll get smashed.
// First we split the string into an array. Then the "sort" function sorts the array of strings in descending length order, so now we have the longest word in the first place.
}

console.log(findLongestWord("The big blue waves smashed over the shiny coast"));

// This array would output like this:

// ['smashed',
// 'waves',
// 'shiny',
// 'coast',
// 'blue',
// 'over',
// 'The',
// 'big',
// 'the' ]

// We don't want to focus on this solution because I need to get the logic.

Titlecasing a sentence

// We are going to titlecase a sentence.
// We want to return the provided string with the first letter of each word capitalized, making sure that the rest of the word is in lower case. We shoudl also capitalize connecting words such as "the" and "of".
// We are given a string and we have to titlecase it.

function titleCase(str) {
var words = str.toLowerCase().split(" "); // We need to separate them into individual words and we also need to lower case all of them.
console.log(words);
}

titleCase("I'm a little teapot");

// Now that we split the string into an array, this code would output:

// [ "i'm", 'a', 'little', 'teapot' ]

function titleCase(str) {
var words = str.toLowerCase().split(" "); // We need to separate them into individual words and we also need to lower case all of them.
for (var i=0; i<words.length; i++) { // Now what we need to do is a normal loop to gro through each word.
// Every time we go through the word, we have to change that word to titlecase.
words[i] = words[i][0].toUpperCase() + words[i].slice(1);
// (we access the array with "words". Then "i" because that changes every time we loop. And every loop, we change the word to what? We change it to what comes after =)
// We use the [i][0] to specify the first letter of the the word in the array, remember that i changes every loop, but we always want the first letter of the string (each word) in the array).
// Once we upper case the first letter of the word, we want the rest of the word, that's why we use the .slice and the number 1 because we want everything on the string starting on the second character.
}
console.log (words);

// Bassically, we are upper casing the first letter and then, we add the rest of the word to that uppercased letter, and we are storing the value of that in words{i].
  
}

titleCase("I'm a little teapot");   

// This code would output an array:

[ "I'm", 'A', 'Little', 'Teapot' ]

// But we don't want an array, we want to output a sentence, so we have to join the strings of the new uppercased array:

function titleCase(str) {
var words = str.toLowerCase().split(" ");
for (var i=0; i<words.length; i++) {
words[i] = words[i][0].toUpperCase() + words[i].slice(1);
}
return words.join(" ");
}
titleCase("I'm a little teapot");

Largest Number

// We want to know the largest number in several arrays, we are given a two dimensional array (arrays within an array), basically, arrays as elements of an array.
// To solve this problem

function largestOfFour(arr) {
var maxes = []; // We create this variable that will store the max number in each array.
// Now we'll loop over the array.
for (var i=0; i<arr.length; i++) {
console.log (arr[i]);
}
}

largestOfFour([[4, 5, 1, 3],[13, 27, 18, 26], [32, 35, 37, 39],[1000, 1001, 857, 1]]);

// This code will output:

/*
$ node P6_LargestNumbers.js
[ 4, 5, 1, 3 ]
[ 13, 27, 18, 26 ]
[ 32, 35, 37, 39 ]
[ 1000, 1001, 857, 1 ]
*/

// We have each array deployed now, but we need to find the max number in each inner array, and for that we need another loop, specifically a nested loop:

function largestOfFour(arr) {
var maxes = [];
for (var i=0; i<arr.length; i) {
for (var ii=0; ii<arr[i].length; ii
) { // We have an inner loop, we are printing through the outer loop over each element (which is an array itself), but we need to print each element of each inner array (inner elements within the elements).
console.log(arr[i][ii])
}
}
}

largestOfFour([[4, 5, 1, 3],[13, 27, 18, 26], [32, 35, 37, 39],[1000, 1001, 857, 1]]);

This code would output:
4
5
1
3
13
27
18
26
32
35
37
39
1000
1001
857
1

// Now that we have looped through all the Elements, we have to find the max, we can't just output them like that, so we tweak the code to find the max:

function largestOfFour(arr) {
var maxes = [];
for (var i=0; i<arr.length; i) {
var tempMax = arr[i][0]; // We create this variable, inside of the outer loop.
// What we are saying above is: Every time the outer loop runs, make tempMax equals to the first number of each inner array.
for (var ii=0; ii<arr[i].length; ii
) { // We have an inner loop, we are printing through the outer loop over each element (which is an array itself), but we need to print each element of each inner array (inner elements within the elements).
// to make this more clear, we will make a variable
var currentElement = arr[i][ii]; // This stores each of the elements in the nested array. So now we can call "currentElement" instead of calling [i][j]
if (currentElement >= tempMax) {
tempMax = currentElement; // What we are doing is "is current element (4) higher or equal to the temporary max? If so, it becomes the current temporary max, if no, the previous temporary max stays as it was and we go to the next element of the array."
}
}

        maxes.push(tempMax);                        // We are pushing this tempMax value into the maxes array which is right now empty.
 }
 console.log(maxes);

}

largestOfFour([[4, 5, 1, 3],[13, 27, 18, 26], [32, 35, 37, 39],[1000, 1001, 857, 1]]);

// This code would output:

// [ 5, 27, 39, 1001 ]

// But we also need to know which is the largest number out of this new array made up of the largest numbers of the inner arrays, so:

// To recap, what we are doing is: We are looping through the outer array with a for loop, and then using another for loop going through the inner arrays. We set the max to the first element in the inner array and comparing it to the tempMax (temporary max) and if it is higher, make that the tempMax. Once the inner loop is done, we push that tempMax value into the new empty array called maxes. Then the loop goes to the next inner array ([i][0]) which becomes [i][0], the inner for loop runs and pushes the tempMax value in that array, and so on.

function largestOfFour(arr) {
var maxes = [];
for (var i=0; i<arr.length; i) {
var tempMax = arr[i][0];
for (var ii=0; ii<arr[i].length; ii
) {
var currentElement = arr[i][ii];
if (currentElement >= tempMax) {
tempMax = currentElement;
}
}
maxes.push(tempMax);
}
console.log(maxes);
}

largestOfFour([[4, 5, 1, 3],[13, 27, 18, 26], [32, 35, 37, 39],[1000, 1001, 857, 1]]);

// Every time we have a nested problem, we can just divide the problem into several little problems.

Confirm Ending

// We are supposed to check if the string ends with the give target string.

function confirmEnding(str, target) {
if (str.endsWith(target)) { // The .endsWith() method comes with Javascript, we just need to know how to use it.
return true;
}
return false;
}

console.log(confirmEnding("Bastian", "n")); // We use console.log because Visual Studio doesn't return true or false when we run the code as is :(

// There is another way of writing this code, an easier way:

function confirmEnding(str, target) {
return str.endsWith(target); // If its true, it will return true, if not, it will return false.
}
console.log (confirmEnding("Bastian", "n")); // Again, we use console.log because VSC is crap.

// There is also a way to solve this by using a substring method from JS:

// Let's say we have a string:

var sentence ="I am running home in 5 minutes.";

console.log(sentence.substr(0, 7)) // substring (.substr) takes two parameters, the first one is the index where the sub string will begin and the second one tells us how many indexes it will take, in this case its 5.

// This code will output: I am ru

// To use this method in the function and know if the target matches the encodeURI, we have to:

var sentence ="I am running home in 5 minutes.";

console.log(sentence.substr(-4, 7)) // If we use negative numbers for first parameter, the .substr method starts counting the indexes from last to first, and will begin the substring where we tell it to, in this case it will begin in the fourth index from last to first.

// This code would output: tes.

// We can then use the .substr method to establish the target, and we will know if the string ending matches the target.

function confirmEnding(str, target) {
if (str.substr(-1, 1) === target) { // We use "if" to get a boolean of true or false. We use -1, 1 because we want the last letter and we want it to be one index long.
return true;
}
return false;
}

console.log(confirmEnding("Bastian", "n"));

function confirmEnding(str, target) {
if (str.substr(-target.length) === target) { // We use -target.length to establish that we want to make the substring as long as the target length, no matter how long the sentence is and no matter how long the target is.
return true;
}
return false;
}

console.log(confirmEnding("Bastian", "n"));

// We could also do this in one line of code now that we know the logic:

function confirmEnding(str, target) {
return str.substr(-target.length) === target;
}
confirmEnding("Bastian", "n");

// The method .slice also works instead of using .substr

var sentence = "hello"
console.log (sentence.length)

Repeat String

// We have to repeat a given string (first argument) "num" times (a second argument). Return an empty string if "num" is not a positive Number.

function repeatStringNumTimes(str, num) {

}

repeatStringNumTimes("abc", 3);

// The first method we can use to solve this, by keeping it simple, is an "if" function and the method str.repeat

function repeatStringNumTimes(str, num) {
if (num < 0) return "";
return str.repeat(num);
}

console.log(repeatStringNumTimes("abc", 3));

// This method is cool, but we rely on a method, there are different ways of solving this problem and we can actually use a for loop:

function repeatStringNumTimes(str, num) {
var final = "";
if (num < 0) return "";

for (var i=0; i < num; i++) {         // We re running the loop "num" times, and it will add str (the first parameter) to final, four times (the num).
   final += str;
}
return final;

}
console.log(repeatStringNumTimes("abc", 3));



That's it for today, this was way much harder to solve than to post, but I wanted to share it with you in case someone is looking for the freecodecamp javascript problems solutions, I got your back.

Have a great week Hivemigos!

H2
H3
H4
3 columns
2 columns
1 column
6 Comments
Ecency