Wednesday, July 3, 2024
HomeLanguagesJavascriptJavaScript Program to find Smallest and Largest Word in a String

JavaScript Program to find Smallest and Largest Word in a String

In this article, we are going to discuss how can we find the Smallest and Largest word in a string. The word in a string which will have a smaller length will be the smallest word in a string and the word that has the highest length among all the words present in a given string will be the Largest word in a string.

There are a few approaches by which we can find the Smallest and Largest word in a string:

  • Using Regular Expression
  • Using reduce method
  • Using for loop

Using Regular Expressions

In this approach, we are using \w+ regex pattern, “str.match()“extracts words from the input string. We then use the map() method to find the smallest and largest words by comparing their lengths and we will Return an object containing these words.

Example: In this example, The myFunction JavaScript function takes a string input, extracts individual words, and finds the smallest and largest words based on their lengths. It uses regular expressions to match words, initializes variables for the smallest and largest words, and iterates through the words to update these variables.

Javascript




function myFunction(str) {
    const words = str.match(/\b\w+\b/g);
    if (!words) return { smallest: "", largest: "" };
  
    let smallest = words[0];
    let largest = words[0];
  
    words.map(word => {
        if (word.length < smallest.length) {
            smallest = word;
        }
        if (word.length > largest.length) {
            largest = word;
        }
    });
  
    return { smallest, largest };
}
  
let inputStr = 
    "neveropen is a computer science portal.";
let result = myFunction(inputStr);
console.log(result);


Output

{ smallest: 'a', largest: 'neveropen' }

Time Complexity: O(n), where n is the length of the input string.

Space Complexity: O(k), where k is the number of words in the input string.

Using reduce() method

In this approach, we are using reduce() method, we will split the string into words by using split() method then we will initialize smallest and largest variabel having the first word as a value then iterate through the whole string and updating them based on length comparisons. And at last return the smallest and largest words.

Example: This example shows the use of the above-explained approach.

Javascript




function myFunction(str) {
    let words = str.split(' ');
  
    if (words.length === 0) {
        return { smallest: "", largest: "" };
    }
    let smallest = words.reduce((a, b) =>
        (a.length <= b.length ? a : b));
    let largest = words.reduce((a, b) =>
        (a.length >= b.length ? a : b));
  
  
    return { smallest, largest };
}
  
let inputStr =
    "neveropen is a computer science portal.";
let result = myFunction(inputStr);
console.log(result);


Output

{ smallest: 'a', largest: 'neveropen' }

Time Complexity: O(n), where n is the length of the input string.

Space Complexity: O(k), where k is the number of words in the input string.

Using for loop

In this approach, The myFunction JavaScript function splits the input string into words, initializes variables for the smallest and largest word, and iterates through the words to find the smallest and largest word among them . At last or end of iteration It returns an object containing the smallest and largest words.

Example: This example shows the use of the above-explained approach.

Javascript




function myFunction(str) {
    let words = str.split(' ');
    if (words.length === 0) {
        return { smallest: "", largest: "" };
    }
      
    let smallest = words[0];
    let largest = words[0];
      
    for (let i = 1; i < words.length; i++) {
        let word = words[i];
        if (word.length < smallest.length) {
            smallest = word;
        }
        if (word.length > largest.length) {
            largest = word;
        }
    }
    return { smallest, largest };
}
  
let inputStr = "neveropen a computer science portal.";
let result = myFunction(inputStr);
console.log(result);


Output

{ smallest: 'a', largest: 'neveropen' }

Time Complexity: O(n), where n is the number of words in the input string.

Space Complexity: O(1), as the function maintains only a constant amount of extra space regardless of the input size.

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

Nokonwaba Nkukhwana
Experience as a skilled Java developer and proven expertise in using tools and technical developments to drive improvements throughout a entire software development life cycle. I have extensive industry and full life cycle experience in a java based environment, along with exceptional analytical, design and problem solving capabilities combined with excellent communication skills and ability to work alongside teams to define and refine new functionality. Currently working in springboot projects(microservices). Considering the fact that change is good, I am always keen to new challenges and growth to sharpen my skills.
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments