Introduction
This challenge is about finding the longest word in a sentence. Imagine you have a bunch of words in a paragraph, and your job is to figure out which word is the longest by counting its characters. To solve this challenge, we need to convert a given string into an array and then begin the operation.
Examples:
- let str1 = ‘This is a long sentence’ so sentence is our output because it is the longest word in this whole string.
- let str2 = ‘The quick brown fox jumped over the lazy dog’ now our output will be jumped.
Remember: There are numerous ways to solve specific coding challenges in programming, but we will explore one of them here.
Breaking Down the Problem:
Suppose we have the string and we want to get the longest words from it. To achieve this, we need to convert the string into an array as we know we cannot directly apply an if/else condition to a string in sentence form. Let’s start coding to better understand the process.
let str1 = 'This is a long sentence'
Next, we need to convert it into an array so that we can apply the if/else condition to it. We will use split() a JavaScript built-in method for conversion.
let strArray = str1.split(' ');
Ensure there is a single space between the quotation marks; otherwise, unexpected results may occur.
Now, we have to declare a variable for getting the first values from the array. We will discuss it later.
let greaterWord = strArray[0];
Now, we have successfully obtained the first value from the array. Let's try to understand that I used strArray[0], which means the value at the first index. As we know, in JavaScript, indexing starts from 0, not 1. That is why our first value is at index 0, and we can access values using the index.
Now it's time to initiate a for loop to access all the values from this array. This will enable us to apply if/else conditions.
for (let i = 1; i < strArray.length; i++) {
if (strArray[i].length > greaterWord.length) {
greaterWord = strArray[i];
}
}
Let’s try to understand the code we wrote. Inside the loop, we initiated the condition to check which word is the longest in the sentence. We employed if (strArray[i].length > greaterWord.length) to identify the longest word in the sentence. Now we successfully solved our challenge.
Full Function
let str1 = 'This is a long sentence';
function longestWord(str1) {
let strArray = str1.split(' ');
let greaterWord = strArray[0];
for (let i = 1; i < strArray.length; i++) {
if (strArray[i].length > greaterWord.length) {
greaterWord = strArray[i];
}
}
return greaterWord;
}
console.log(longestWord(str1)); // output: sentence