I already know that the largest string within the array has 12 letters, how do I display the value of this String, which in this case is "rioDeJaneiro"?
var cidades = ["Sãopaulo", "Riodejaneiro", "Fortaleza"]
var biggerWord = 0
for (var i = 0; i < cidades.length; i++) {
console.log(cidades[i].length)
if (cidades[i].length > biggerWord) {
biggerWord = cidades[i].length
}
}
console.log("--------------------------------------------------")
console.log("A maior palavra tem: " + biggerWord)
I already looked for methods in the documentation but I couldn’t find them.
var cidades = ["Sãopaulo", "Riodejaneiro", "Fortaleza"]
var biggerWord = 0
for (var i = 0; i < cidades.length; i++) {
console.log(cidades[i].length)
if (cidades[i].length > biggerWord) {
biggerWord = cidades[i].length
}
}
console.log("--------------------------------------------------")
console.log("A maior palavra tem: " + biggerWord)
6
Answers
Save the longest word, or the index of the longest word, instead of its length. When you have the longest word or its array index then you can access the value and any other derived "data" from it, like its length easily.
Examples:
You can use reduce, this way:
Way 1:
Way 2:
Here we will talk about how to use JavaScript properly To show off position and value of the largest string in an array, based on the length of string that is used.
javascript
let arr = [‘apple’, ‘banana’, ‘strawberry’, ‘kiwi’,’pineapple’];
let largestString = arr. (y, x) => y.length > x.length? a : b);
let position = arr. indexOf(largestString);
console. log(
Position: ${position}, Value: ${largestString}
)In this case the output will be aware of this array: []
Rank: 2, Fruit: strawberry
Edit, answer lacked a reduce call to be valid JS, correct example below
First declare a stringArr to be used in example
Then find the longest string by comparing using the JS function "reduce", and assign that to const longestString.
The reduce function takes whatever is returned from the function and uses it on the next index of the array, so here we simply compare the length of currentIndex with whatever the current returned value is (longeststring). then returns which of those are the longest.
Finally, console log to prove its correctly implemented
Here is a version that is still O(n) but avoids
https://jsperf.app/jadapa
All this is of course irrelevant for 3 words.
Another alternative is;