I'm learning JavaScript, and practicing I came across this exercise which I don't know how to solve, thanks in advance to whoever can explain how and why.
Assignment of the exercise:Given these three arrays:
carnivores = ['lion', 'shark', 'wolve', 'puma', 'snake'];
herbivores = ['elephant', 'giraffe', 'gacelle', 'hippo', 'koala'];
omnivores = ['human', 'monkey', 'dog', 'bear', 'pig'];
Define a variable called animals that references the previous arrays: [carnivores, herbivores, omnivores].
Create a FOR loop that changes each string in the array for each diet to be plural. For example: ['lion',...] -> ['lions',...]
Where I have problems to solve is in point 2, I leave you my code:
var carnivores = ['lion', 'shark', 'wolve', 'puma', 'snake'];
var herbivores = ['elephant', 'giraffe', 'gacelle', 'hippo', 'koala'];
var omnivores = ['human', 'monkey', 'dog', 'bear', 'pig'];
var animals = [].concat(carnivores, herbivores, omnivores);
although the for each is the best to do that, here is a quick and simple answer:
you set "animal" to zero and loop through the array, there you simply take each element of the array (animals[animal]) which is a string, and add the 's'
To solve with what you are suggesting, you could do the following, simply go through animals, which is the result of the concatenation of all the arrays and add an "s" to all the elements.
According to the letter animal, it is an array that refers to the previous ones, after each array each item is traversed adding the "s". In that case, you could do something like this:
In this example, the array of animals is traversed and used as a reference to traverse each array in the first for, in the second it traverses each item within that array and adds an "s" to each item at the end.
Some possible improvements could be the following: This example does the same as the previous one, only instead of using 2 conventional fors, it uses a for of, which will help readability. Also in the assignment += is used, so that this is understood: it
a = a + b
is equivalent toa += b
.In these last 2 examples the animals variable just references the different arrays, and the arrays remain as they were but each item is now plural.