I'm trying to find the way to obtain the longest words of each array:
var carnivores = ['lion', 'shark', 'wolve', 'puma', 'snake'];
var herbivores = ['elephant', 'giraffe', 'gacelle', 'hippo', 'koala'];
var omnivores = ['human', 'monkey', 'dog', 'bear', 'pig'];
Then I create a multidimensional-array:
var animals = [carnivores, herbivores, omnivores];
In order to obtain the longest words of each array I do this:
var carnivores = ['lion', 'shark', 'wolve', 'puma', 'snake'];
var herbivores = ['elephant', 'giraffe', 'gacelle', 'hippo', 'koala'];
var omnivores = ['human', 'monkey', 'dog', 'bear', 'pig'];
var animals = [carnivores, herbivores, omnivores];
function longestAnimals() {
var longest = "";
for (var i = 0; i < animals.length; i++) {
for (var j = 0; j < animals[i].length; j++) {
if (animals[i][j].length > longest.length) {
longest = animals[i][j];
}
}
}
return longest;
}
console.log(longestAnimals());
My code returns the longest word of all the array, it shows only elephant. What can I do to obtain shark, elephant, and monkey. Thank you!
Now you are looping and finding only one value.
It is needed to make the longest as array and whenever the j loop finishes, push the item for that sub array as follows.
var carnivores = ['lion', 'shark', 'wolve', 'puma', 'snake'];
var herbivores = ['elephant', 'giraffe', 'gacelle', 'hippo', 'koala'];
var omnivores = ['human', 'monkey', 'dog', 'bear', 'pig'];
var animals = [carnivores, herbivores, omnivores];
function longestAnimals() {
var longest = [];
for (var i = 0; i < animals.length; i++) {
var longestItem = "";
for (var j = 0; j < animals[i].length; j++) {
if (animals[i][j].length > longestItem.length) {
longestItem = animals[i][j];
}
}
longest.push(longestItem);
}
return longest;
}
console.log(longestAnimals());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With