Last active
April 5, 2023 14:45
-
-
Save DevGW/c9e80dedea777b760a00619c1f970e2d to your computer and use it in GitHub Desktop.
Javascript :: Arrays III : Spreading #js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Takes a formatted multidimensional array and outputs sentences using constants: | |
function zooInventory(aZoo) { | |
let animalFacts = []; | |
for (let i=0; i < aZoo.length; i++) { | |
const currentAnimal = aZoo[i]; | |
const animalName = currentAnimal[0]; | |
const animalType = currentAnimal[1][0]; | |
const animalAge = currentAnimal[1][1]; | |
animalFacts.push(`${animalName} the ${animalType} is ${animalAge}.`); | |
} | |
return animalFacts; | |
} | |
// the same thing but refactored to use array spreading: | |
function zooInventory(aZoo) { | |
let animalFacts = []; | |
for (let i=0; i < aZoo.length; i++) { | |
const [animalName, [animalType, animalAge]] = aZoo[i]; | |
animalFacts.push(`${animalName} the ${animalType} is ${animalAge}.`); | |
} | |
return animalFacts; | |
} | |
//when given this as a starting point: | |
let myZoo = [ | |
['King Kong', ['gorilla', 42]], | |
['Nemo', ['fish', 5]], | |
['Punxsutawney Phil', ['groundhog', 11]] | |
]; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment