Abu bakkar siddique
Abu bakkar siddique

Reputation: 49

How to find the length of the largest word in a string with javascript?

function findLongestWordLength(str) {
  var res = str.split(" ");
  var ar = [];
  for (let i = 0; i <
    res.length; i++) {
    let leength = res[i].length;
    ar.push(leength);
    //ar is the array of the lengths of the word in the string.
  }
  var largest = 0;
  for (let i = 0; i <=
    largest; i++) {
    if (ar[i] > largest) {
      var largest = ar[i];
    } //this loop is detecting largest number from the array ar.
  }
  return largest;
}
console.log(findLongestWordLength("What if we try a super-long word such as otorhinolaryngology"));

I want the largest word length from a string,

This is working for maximum string but is not working for this coressponding array "What if we try a super-long word such as otorhinolaryngology"

Upvotes: 2

Views: 85

Answers (3)

Shiva kumar
Shiva kumar

Reputation: 11

//Let us take an example

let givenSen = "Shiva is a good guy";

//Here we are splitting with space 
//So we will get ["Shiva", "is", "a", "good", "guy"]
//and sorting based on length
//remeber a-b (ascending order), b-a (decending order)
//0(zero) represents first element

let largestWord = givenSen.split(" ").sort(function(a,b){return(b.length - a.length)})[0]

//cosole

console.log(largestWord.length)

Upvotes: 0

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521349

Try splitting the input on whitespace, then sorting the array by length:

var input = "What if we try a super-long word such as otorhinolaryngology";
var parts = input.split(/\s+/);
parts.sort(function(a, b) { return b.length - a.length; });
console.log(parts[0]);

Upvotes: 1

CertainPerformance
CertainPerformance

Reputation: 370779

You have

var largest = 0;
for (let i = 0; i <= largest; i++) {

You're iterating over the ar from indicies 0 to whichever index first sets largest to something larger than the current index. Use i < ar.length instead:

function findLongestWordLength(str) {
  var res = str.split(" ");
  var ar = [];
  for (let i = 0; i < res.length; i++) {
    let leength = res[i].length;
    ar.push(leength);
    //ar is the array of the lengths of the word in the string.
  }
  var largest = 0;
  for (let i = 0; i < ar.length; i++) {
    if (ar[i] > largest) {
      var largest = ar[i];
    } //this loop is detecting largest number from the array ar.
  }
  return largest;
}
console.log(findLongestWordLength("What if we try a super-long word such as otorhinolaryngology"))

But spreading the mapped word lengths into Math.max might be easier:

const findLongestWordLength = str => Math.max(
  ...str.split(' ').map(word => word.length)
);
console.log(findLongestWordLength("What if we try a super-long word such as otorhinolaryngology"))

Upvotes: 3

Related Questions