challenge-algorithms-v2.0/10-longestWords/index.js

24 lines
847 B
JavaScript

function longest(str){
// Split the string using regex
str = str.match(/[a-zA-Z0-9]+/gi);
// Creating a empty string to store largest word
let largest = "";
// Creating a for...loop to iterate over the array
for(let i = 0; i < str.length; i++){
// If the i'th item is greater than largest string
// then overwrite the largest string with the i'th value
if(str[i].length > largest.length){
largest = str[i]
}
}
return largest;
}
console.log(longest(["abacaxi", "melancia", "banana"]));
console.log(largest(["aba", "aa", "ad", "vcd", "aba"]));
console.log(largest(["aa"]));
console.log(largest(["abc", "eeee", "abcd", "dcd"]));
console.log(largest(["aa", "bb", "cc"]));
console.log(largest(["a", "abc", "cbd", "zzzzzz", "a", "abcdef", "asasa", "aaaaaa"]));