create the following JS functions A. maxWord function Write and test a function
ID: 3938293 • Letter: C
Question
create the following JS functions
A. maxWord function
Write and test a function named maxWord that accepts an array of strings and returns the long word in the array.
Example:
maxWord(["The", "albatross", "just", "ate", "your", "lunch"]) => "Albatross"
B. maxWordSentence function
Write and test a function named maxWordSentence that accepts a string representing a sentence, and returns the longest word in the sentence. Words in a sentence are delimited by spaces, and sentences do not contain any punctuation. Hint: split().
Example:
maxWordSentence("The albatross just ate your lunch") => "Albatross"
Explanation / Answer
Please find the required program along with its output. Please see the comments against each line to understand the step.
A)
function maxWord(arr) {
var max = 0;
var maxWd = "";
for (var i in arr){ //iterate through all elements in array arr
if(arr[i].length > max){ //if the current elements length is > max
max = arr[i].length; //set max to current elements length
maxWd = arr[i]; //set maxWd to current element
}
}
return maxWd; //return the maxWd
}
var arr = ["The", "albatross", "just", "ate", "your", "lunch"];
document.write("maxWord = "+maxWord(arr));
-------------------------------------------
OUTPUT:
B)
function maxWordSentence(str){
var arr = str.split(" "); //split the given sentence based on spaces
return maxWord(arr); //call and return the value of maxWord function
}
function maxWord(arr) {
var max = 0;
var maxWd = "";
for (var i in arr){ //iterate through all elements in array arr
if(arr[i].length > max){ //if the current elements length is > max
max = arr[i].length; //set max to current elements length
maxWd = arr[i]; //set maxWd to current element
}
}
return maxWd; //return the maxWd
}
document.write("maxWord in sentence = "+maxWordSentence("The albatross just ate your lunch"));
------------------------------------------
OUTPUT:
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.