Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to obtain the longest words in a multidimensional array?

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!

like image 878
S.Marx Avatar asked Jan 23 '26 05:01

S.Marx


1 Answers

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());
like image 153
Derek Wang Avatar answered Jan 24 '26 17:01

Derek Wang