0% found this document useful (0 votes)
29 views15 pages

Tech Notes... 21062023

The document describes three ways to find the longest word in a string in JavaScript: 1) Using a for loop to iterate through each word and track the longest, 2) Sorting the words by length and returning the first, and 3) Using reduce() to iteratively track the longest word. It also provides two approaches for confirming the ending of a string and returning the largest numbers in arrays: using substr() to check the ending and a nested for loop to iterate through each sub-array and track the largest value.

Uploaded by

Adedotun Omonijo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views15 pages

Tech Notes... 21062023

The document describes three ways to find the longest word in a string in JavaScript: 1) Using a for loop to iterate through each word and track the longest, 2) Sorting the words by length and returning the first, and 3) Using reduce() to iteratively track the longest word. It also provides two approaches for confirming the ending of a string and returning the largest numbers in arrays: using substr() to check the ending and a nested for loop to iterate through each sub-array and track the largest value.

Uploaded by

Adedotun Omonijo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 15

Three Ways to Find the Longest Word in a String in JavaScript

1. Find the longest word with a FOR Loop


For this solution, we will use the String.prototype.split() method
The split() method splits a String object into an array of strings by
separating the string into sub strings.
function findLongestWord(str) {
// Step 1. Split the string into an array of strings
var strSplit = str.split(' ');
// var strSplit = "The quick brown fox jumped over the lazy dog".split(' ');
// var strSplit = ["The", "quick", "brown", "fox", "jumped", "over", "the", "lazy", "dog"];

// Step 2. Initiate a variable that will hold the length of the longest word
var longestWord = 0;

// Step 3. Create the FOR loop


for(var i = 0; i < strSplit.length; i++){
if(strSplit[i].length > longestWord){ // If strSplit[i].length is greater than the word it is
compared with...
longestWord = strSplit[i].length; // ...then longestWord takes this new value
}
}
/* Here strSplit.length = 9
For each iteration: i = ? i < strSplit.length? i++ if(strSplit[i].length > longestWord)? longestWord =
strSplit[i].length
1st iteration: 0 yes 1 if("The".length > 0)? => if(3 > 0)? longestWord = 3
2nd iteration: 1 yes 2 if("quick".length > 3)? => if(5 > 3)? longestWord = 5
3rd iteration: 2 yes 3 if("brown".length > 5)? => if(5 > 5)? longestWord = 5
4th iteration: 3 yes 4 if("fox".length > 5)? => if(3 > 5)? longestWord = 5
5th iteration: 4 yes 5 if("jumped".length > 5)? => if(6 > 5)? longestWord = 6
6th iteration: 5 yes 6 if("over".length > 6)? => if(4 > 6)? longestWord = 6
7th iteration: 6 yes 7 if("the".length > 6)? => if(3 > 6)? longestWord = 6
8th iteration: 7 yes 8 if("lazy".length > 6)? => if(4 > 6)? longestWord = 6
9th iteration: 8 yes 9 if("dog".length > 6)? => if(3 > 6)? longestWord = 6
10th iteration: 9 no
End of the FOR Loop*/
//Step 4. Return the longest word
return longestWord; // 6
}

findLongestWord("The quick brown fox jumped over the lazy dog");

2.) Find the Longest Word With the sort() Method


For this solution, we will use the Array.prototype.sort() method to sort
the array by some ordering criterion and then return the length of the
first element of this array.
function findLongestWord(str) {
// Step 1. Split the string into an array of strings
var strSplit = str.split(' ');
// var strSplit = "The quick brown fox jumped over the lazy dog".split(' ');
// var strSplit = ["The", "quick", "brown", "fox", "jumped", "over", "the", "lazy", "dog"];

// Step 2. Sort the elements in the array


var longestWord = strSplit.sort(function(a, b) {
return b.length - a.length;
});
/* Sorting process
a b b.length a.length var longestWord
"The" "quick" 5 3 ["quick", "The"]
"quick" "brown" 5 5 ["quick", "brown", "The"]
"brown" "fox" 3 5 ["quick", "brown", "The", "fox"]
"fox" "jumped" 6 3 ["jumped", quick", "brown", "The", "fox"]
"jumped" "over" 4 6 ["jumped", quick", "brown", "over", "The", "fox"]
"over" "the" 3 4 ["jumped", quick", "brown", "over", "The", "fox", "the"]
"the" "lazy" 4 3 ["jumped", quick", "brown", "over", "lazy", "The", "fox", "the"]
"lazy" "dog" 3 4 ["jumped", quick", "brown", "over", "lazy", "The", "fox", "the",
"dog"]
*/

// Step 3. Return the length of the first element of the array


return longestWord[0].length; // var longestWord = ["jumped", "quick", "brown", "over", "lazy",
"The", "fox", "the", "dog"];
// longestWord[0]="jumped" => jumped".length => 6
}
findLongestWord("The quick brown fox jumped over the lazy dog");

3. Find the Longest Word With the reduce() Method


For this solution, we will use the Array.prototype.reduce().
The reduce() method applies a function against an accumulator and each
value of the array (from left-to-right) to reduce it to a single value.
Reduce() executes a callback function once for each element present in the
array.
function findLongestWord(str) {
// Step 1. Split the string into an array of strings
var strSplit = str.split(' ');
// var strSplit = "The quick brown fox jumped over the lazy dog".split(' ');
// var strSplit = ["The", "quick", "brown", "fox", "jumped", "over", "the", "lazy", "dog"];

// Step 2. Use the reduce method


var longestWord = strSplit.reduce(function(longest, currentWord) {
if(currentWord.length > longest.length)
return currentWord;
else
return longest;
}, "");

/* Reduce process
currentWord longest currentWord.length longest.length if(currentWord.length >
longest.length)? var longestWord
"The" "" 3 0 yes "The"
"quick" "The" 5 3 yes "quick"
"brown" "quick" 5 5 no "quick"
"fox" "quick" 3 5 no "quick"
"jumped" "quick" 6 5 yes "jumped"
"over" "jumped" 4 6 no "jumped"
"the" "jumped" 3 6 no "jumped"
"lazy" "jumped" 4 6 no "jumped"
"dog" "jumped" 3 6 no "jumped"
*/
// Step 3. Return the length of the longestWord
return longestWord.length; // var longestWord = "jumped"
// longestWord.length => "jumped".length => 6
}

findLongestWord("The quick brown fox jumped over the lazy dog");

Two ways to confirm the ending of a String in JavaScript


Approach #1: Confirm the Ending of a String With Built-In Functions — with
substr()
For this solution, you’ll use the String.prototype.substr() method:
The substr() method returns the characters in a string beginning at the
specified location through the specified number of characters.
String.substr(-target.length)?- If the target.length is negative, the substr()
method will start the counting from the end of the string, which is what you
want in this code challenge. You do not use string.substr(-1) to get the
last element of the string if the target is longer than one letter, because the
target won’t return at all.
In this instance, string.substr(-target.length) will get the last index of the
string ‘Bastian’ which is ‘n’.
Then you check whether string.substr(-target.length) equals the target
(true or false).
Return Largest Numbers in Arrays
Approach #1: Return the Largest Numbers in an Array with a For Loop

function largestOfFour(arr) {
// Step 1. Create an array that will host the result of the 4 sub-arrays
var largestNumber = [0,0,0,0];

// Step 2. Create the first FOR loop that will iterate through the arrays
for(var arrayIndex = 0; arrayIndex < arr.length; arrayIndex++) {
/* The starting point, index 0, corresponds to the first array */

// Step 3. Create the second FOR loop that will iterate through the sub-arrays
for(var subArrayIndex = 0; subArrayIndex < arr[arrayIndex].length; subArrayIndex+
+) {
/* The starting point, index 0, corresponds to the first sub-array */

if(arr[arrayIndex][subArrayIndex] > largestNumber[arrayIndex]) {

largestNumber[arrayIndex] = arr[arrayIndex][subArrayIndex];

/* FOR loop cycles


arrayIndex => i
subArrayIndex => j

Iteration in the first array


For each iteration: arr[i][j] largestNumber[i] if arr[i][j] > largestNumber[i]? then
largestNumber[i] = arr[i][j]
First iteration: arr[0][0] => 4 largestNumber[0] => 0 4 > 0? => TRUE then
largestNumber[0] = 4
Second iteration: arr[0][1] => 5 largestNumber[0] => 4 5 > 4? => TRUE then
largestNumber[0] = 5
Third iteration: arr[0][2] => 1 largestNumber[0] => 5 1 > 5? => FALSE then
largestNumber[0] = 5
Fourth iteration: arr[0][3] => 3 largestNumber[0] => 5 3 > 5? => FALSE then
largestNumber[0] = 5
Fifth iteration: arr[0][4] => FALSE largestNumber[0] => 5
largestNumber = [5,0,0,0]
Exit the first array and continue on the second one
Iteration in the second array
For each iteration: arr[i][j] largestNumber[i] if arr[i][j] > largestNumber[i]? then
largestNumber[i] = arr[i][j]
First iteration: arr[1][0] => 13 largestNumber[1] => 0 13 > 0? => TRUE then
largestNumber[1] = 13
Second iteration: arr[1][1] => 27 largestNumber[1] => 13 27 > 13? => TRUE
then largestNumber[1] = 27
Third iteration: arr[1][2] => 18 largestNumber[1] => 27 18 > 27? => FALSE
then largestNumber[1] = 27
Fourth iteration: arr[1][3] => 26 largestNumber[1] => 27 26 > 27? => FALSE
then largestNumber[1] = 27
Fifth iteration: arr[1][4] => FALSE largestNumber[1] => 27
largestNumber = [5,27,0,0]
Exit the first array and continue on the third one
Iteration in the third array
For each iteration: arr[i][j] largestNumber[i] if arr[i][j] > largestNumber[i]? then
largestNumber[i] = arr[i][j]
First iteration: arr[2][0] => 32 largestNumber[2] => 0 32 > 0? => TRUE then
largestNumber[2] = 32
Second iteration: arr[2][1] => 35 largestNumber[2] => 32 35 > 32? => TRUE
then largestNumber[2] = 35
Third iteration: arr[2][2] => 37 largestNumber[2] => 35 37 > 35? => TRUE then
largestNumber[2] = 37
Fourth iteration: arr[2][3] => 39 largestNumber[2] => 37 39 > 37? => TRUE
then largestNumber[2] = 39
Fifth iteration: arr[2][4] => FALSE largestNumber[2] => 39
largestNumber = [5,27,39,0]
Exit the first array and continue on the fourth one
Iteration in the fourth array
For each iteration: arr[i][j] largestNumber[i] if arr[i][j] > largestNumber[i]? then
largestNumber[i] = arr[i][j]
First iteration: arr[3][0] => 1000 largestNumber[3] => 0 1000 > 0? => TRUE then
largestNumber[3] = 1000
Second iteration: arr[3][1] => 1001 largestNumber[3] => 1000 1001 > 1000? => TRUE
then largestNumber[3] = 1001
Third iteration: arr[3][2] => 857 largestNumber[3] => 1001 857 > 1001? => FALSE
then largestNumber[3] = 1001
Fourth iteration: arr[3][3] => 1 largestNumber[3] => 1001 1 > 1001? => FALSE
then largestNumber[3] = 1001
Fifth iteration: arr[3][4] => FALSE largestNumber[3] => 1001
largestNumber = [5,27,39,1001]
Exit the FOR loop */
}
}
}

Approach 2 - Return the Largest Numbers in a Array With Built-In


Functions — with map() and reduce()

For this solution, you’ll use two methods: the Array.prototype.map() method
and the Array.prototype.reduce() method.

if (currentLargestNumber > previousLargestNumber == true) {


return currentLargestNumber;
} else {
return previousLargestNumber;
}

SOLUTION

function largestOfFour(mainArray) {
// Step 1. Map over the main arrays
return mainArray.map(function (subArray){ // Step 3. Return the largest numbers of each sub-arrays
=> returns [5,27,39,1001]

// Step 2. Grab the largest numbers for each sub-arrays with reduce() method
return subArray.reduce(function (previousLargestNumber, currentLargestNumber) {
return (currentLargestNumber > previousLargestNumber) ? currentLargestNumber :
previousLargestNumber;

/* Map process and Reduce method cycles


currentLargestNumber => cLN
previousLargestNumber => pLN
Iteration in the first array
For each iteration: cLN pLN if (cLN > pLN) ? then cLN else pLN
First iteration: 4 0 4 > 0? => TRUE 4 /
Second iteration: 5 4 5 > 4? => TRUE 5 /
Third iteration: 1 5 1 > 5? => FALSE / 5
Fourth iteration: 3 5 3 > 5? => FALSE / 5
Fifth iteration: / 5 returns 5
Exit the first array and continue on the second one
Iteration in the second array
For each iteration: cLN pLN if (cLN > pLN) ? then cLN else pLN
First iteration: 13 0 13 > 0? => TRUE 13 /
Second iteration: 27 13 27 > 13? => TRUE 27 /
Third iteration: 18 27 18 > 27? => FALSE / 27
Fourth iteration: 26 27 26 > 27? => FALSE / 27
Fifth iteration: / 27 returns 27
Exit the first array and continue on the third one
Iteration in the third array
For each iteration: cLN pLN if (cLN > pLN) ? then cLN else pLN
First iteration: 32 0 32 > 0? => TRUE 32 /
Second iteration: 35 32 35 > 32? => TRUE 35 /
Third iteration: 37 35 37 > 35? => TRUE 37 /
Fourth iteration: 39 37 39 > 37? => TRUE 39 /
Fifth iteration: / 39 returns 39
Exit the first array and continue on the fourth one
Iteration in the fourth array
For each iteration: cLN pLN if (cLN > pLN) ? then cLN else pLN
First iteration: 1000 0 1000 > 0? => TRUE 1000 /
Second iteration: 1001 1000 1001 > 1000? => TRUE 1001 /
Third iteration: 857 1001 857 > 1001 => FALSE / 1001
Fourth iteration: 1 1001 1 > 1001? => FALSE / 1001
Fifth iteration: / 1001 returns 1001
Exit the first array and continue on the fourth one */
}, 0); // 0 serves as the context for the first pLN in each sub array
});
}

APPROACH 3:
Return the Largest Numbers in a Array With Built-In Functions — with
map() and apply()
For this solution, you’ll use two methods: the Array.prototype.map()
method and the Function.prototype.apply() method.
You can pass an array of arguments to a function by using the apply()
method and the function will execute the items in the array:

A.) Such functions are known as variadic functions, and they can accept
any number of arguments instead of a fixed one.

B.) The Math.max() function returns the largest of zero or more numbers,
and we can pass any number of arguments.
var num = [4,5,1,3];
console.log(Math.max.apply(null, num)); // logs 5

function largestOfFour(mainArray) {
return mainArray.map(function(subArray) {
return Math.max.apply(null, subArray);
});
}

Repeat a String Repeat a String

Approach #1: Repeat a String with a While Loop


function repeatStringNumTimes(string, times) {
// Step 1. Create an empty string that will host the repeated string
var repeatedString = "";
// Step 2. Set the While loop with (times > 0) as the condition to check
while (times > 0) { // As long as times is greater than 0, the statement is executed
// The statement
repeatedString += string; // Same as repeatedString = repeatedString + string;
times--; // Same as times = times - 1;
}
/* While loop logic
Condition T/F repeatedString += string repeatedString times
First iteration (3 > 0) true "" + "abc" "abc" 2
Second iteration (2 > 0) true "abc" + "abc" "abcabc" 1
Third iteration (1 > 0) true "abcabc" + "abc" "abcabcabc" 0
Fourth iteration (0 > 0) false
}
*/

// Step 3. Return the repeated string


return repeatedString; // "abcabcabc"
}

repeatStringNumTimes("abc", 3);

Approach #2: Repeat a String using a Conditional and Recursion


Recursion is a technique for iterating over an operation by having a function
call itself repeatedly until it arrives at a result. There are a few key features of
recursion that must be included in order for it to work properly.

The first is a base case: this is a statement, usually within a conditional clause
like if, that stops the recursion.
The second is a recursive case: this is the statement where the recursive function
is called on itself.

function repeatStringNumTimes(string, times) {


// Step 1. Check if times is negative and return an empty string if true
if (times <= 0) {
return "";
}

// Step 2. Check if times equals to 1 and return the string itself if it's the case.
if (times === 1) {
return string;
}

// Step 3. Use recursion


else {
return string + repeatStringNumTimes(string, times - 1); // return "abcabcabc";
}
/*
First Part of the recursion method
You need to remember that you won’t have just one call, you’ll have several nested calls
times string + repeatStringNumTimes(string, times - 1)
1st call 3 "abc" + ("abc", 3 - 1)
2nd call 2 "abc" + ("abc", 2 - 1)
3rd call 1 "abc" => if (times === 1) return string;
4th call 0 "" => if (times <= 0) return "";
Second part of the recursion method
4th call will return ""
3rd call will return "abc"
2nd call will return "abc"
1st call will return "abc"
The final call is a concatenation of all the strings
return "abc" + "abc" + "abc"; // return "abcabcabc";
*/
}
repeatStringNumTimes("abc", 3);

Approach #3: Repeat a String using ES6 repeat() method


The repeat() method constructs and returns a new string which contains the
specified number of copies of the string on which it was called, concatenated
together.

if (times > 0) {
return string.repeat(times);
} else {
return "";
}

Truncate a String
Example 1
const str1 = 'This is an example string';
const str2 = 'abc';

const truncate = (str, len) => {


if (str.length > len) {
if (len <= 3) {
return str.slice(0, len - 3) + "...";
}
else {
return str.slice(0, len) + "...";
};
}
else {
return str;
};
};
console.log(truncate(str1, 5));
console.log(truncate(str2, 3));
Using The Sub-String Method
Example 1:
var length = 3;
var myString = "ABCDEFG";
var myTruncatedString = myString.substring(0,length);
Example 2:
var length = 3;
var pathname = document.referrer;
var trimmedPathname = pathname.substring(0, Math.min(length,pathname.length));

document.getElementById("foo").innerHTML =
"<a href='" + pathname +"'>" + trimmedPathname + "</a>"
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.

Method 1
Array.prototype.find()
The find() method returns the first element in the provided array that satisfies the provided
testing function. If no values satisfy the testing function, undefined is returned.
 If you need the index of the found element in the array, use findIndex().
 If you need to find the index of a value, use indexOf(). (It's similar to findIndex(), but
checks each element for equality with the value instead of using a testing function.)
 If you need to find if a value exists in an array, use includes(). Again, it checks each
element for equality with the value instead of using a testing function.
 If you need to find if any element satisfies the provided testing function, use some().
const array1 = [5, 12, 8, 130, 44];

const found = array1.find(element => element > 10);

console.log(found);

function findElement(arr, func) {


return arr.find(func);
}

Method 2
The find() method is an iterative method. It calls a provided callbackFn function once for
each element in an array in ascending-index order, until callbackFn returns a truthy value.
find() then returns that element and stops iterating through the array. If callbackFn never
returns a truthy value, find() returns undefined.

CallbackFn is invoked for every index of the array, not just those with assigned values.
Empty slots in sparse arrays behave the same as undefined

Find Prime Number


1. function primeArr(arr) { 
2.  
3. //Test for Prime Number 
4.  
5. function isPrime(testNo){ 
6.  
7. var result = false; 
8. for(var n = testNo - 1; n > 1; n--){ 
9. result = (testNo % n === 0) + result; 
10. } 
11.  
12. if(result === 0 && testNo > 1){ 
13. return true; 
14. }return false; 
15. } 
16.  
17. //Test for Prime Number 
18.  
19. var newArr = [];  
20.  
21. for(n=0; n<arr.length; n++){ 
22. if(isPrime(arr[n])){ 
23. newArr.push(arr[n]); 
24. } 
25. } 
26.  
27. return newArr; 
28. } 
The function isPrime() returns true if the number, testNo is true
Here is how isPrime() works.
In JavaScript, false + false = 0 and true + true = 2

Basically, when an arithmetic operations is carried out on booleans, 0 is assigned to false and 1 is
assigned to true.

The variable result is initialized with the value false because the integer 0 will not have any effect
on the final result.

The for loop runs through numbers, n, less than testNo. Using the modulus operator (%), it finds
the remainder when testNo is divided by a number, n.

testNo % n // for example: 4 % 2 === 0 and 4 % 3 === 1

When the remainder is 0, it returns true and this means that the number, testNo cannot be a prime
number.

When the remainder is any number > 0, it returns false.

If only false is returned as n reaches 1, this means that the number, testNo is a prime number.

Basically, if the result is greater than 0. It cannot be a prime number.

Next, the if loop checks if result is equal to 0 and if testNo is greater than 1.

(It checks if the testNo is greater than 1 because numbers less than or equals to 1 (zero and one)
are not prime numbers.)

If it passes the condition, it returns true meaning that the number, testNo is a prime number.
And if it returns false, it means the number, testNo is not a prime number.

That is all for the the isPrime() function!

Next, a for loop runs through the values in the array, arr and checks if they pass the isPrime() test.
It returns false if the number arr[n] is not a prime number and it returns true if the number arr[n]
is a prime number.

It is then pushes all the prime numbers to an empty array newArr.


Finally, the return statement outputs the array, newArr

Read at Home Today

You might also like