Skip to content

Instantly share code, notes, and snippets.

@DevGW
Last active April 5, 2023 14:45
Show Gist options
  • Save DevGW/c9e80dedea777b760a00619c1f970e2d to your computer and use it in GitHub Desktop.
Save DevGW/c9e80dedea777b760a00619c1f970e2d to your computer and use it in GitHub Desktop.
Javascript :: Arrays III : Spreading #js
// 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