简体   繁体   中英

How to extract longest word from an array? JavaScript/JSON

I want to create a function that takes a string as its parameter and extracts the longest word. If there are multiple words of the same length (max), It extracts the first one. (By the way, the function ignores numbers and punctuation). Anyways, here's the code:

function extractLongest(testString){
  var lenArr = [];
  var finalResult = "";

window.onload = function(){
  testString = testString.replace(/[^a-z " "]/gi, '');
  testString = testString.split(" ");

  for (var counter = 0; counter < testString.length; counter++){
    lenArr[counter] = parseInt(testString[counter].length);
  }
  lenArr = lenArr.sort();
  for (var counterTwo = 0; counterTwo < testString.length; counterTwo++){
    if(parseInt(testString[counterTwo].length) == Math.max(...lenArr)){
      finalResult = testString[counterTwo];
      break;
    }
  }
 }
return finalResult;
}

The problem is that it always returns "string" (the type of the variable, not its value.)

The problem is your use of window.onload inside a function. This is only setting the handler on the window, which will only run when an onload event fires. Your function does this and then immediately returns finalReuslts which will still be an empty string. Presumably, you want all this code to run when you call the function. It's not clear why you are doing that; removing it makes the function work:

 function extractLongest(testString){ var lenArr = []; var finalResult = ""; testString = testString.replace(/[^az " "]/gi, ''); testString = testString.split(" "); for (var counter = 0; counter < testString.length; counter++){ lenArr[counter] = parseInt(testString[counter].length); } lenArr = lenArr.sort(); for (var counterTwo = 0; counterTwo < testString.length; counterTwo++){ if(parseInt(testString[counterTwo].length) == Math.max(...lenArr)){ finalResult = testString[counterTwo]; break; } } return finalResult; } console.log(extractLongest("hello my name is stephen"))

In case it's useful, there is a simpler way to do this with reduce() :

 function extractLongest(testString){ testString = testString.replace(/[^az " "]/gi, ''); testString = testString.split(" "); return testString.reduce(function(a, b) { return a.length > b.length ? a : b }); } console.log(extractLongest("hello my designation is stephen"))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM