Tengo problemas con un determinado objetivo en el que tengo que crear una función que tome una matriz multidimensional y devuelva una matriz plana con valores de cadena de oraciones usando valores de la matriz multidimensional dada. Tengo dificultades para iterar a través de la matriz y hacer que envíe los valores a una nueva matriz. Todo lo que he probado devuelve los valores en los lugares equivocados y ahora simplemente devuelve undefined . Estoy tan perdido y frustrado
Defina una función, zooInventory , que acepte una matriz multidimensional de hechos de animales. zooInventory debería devolver una matriz nueva y plana de cadenas. Cada elemento de la nueva matriz debe ser una oración sobre cada uno de los animales del zoológico.
let myZoo = [ ['King Kong', ['gorilla', 42]], ['Nemo', ['fish', 5]], ['Punxsutawney Phil', ['groundhog', 11]] ]; function zooInventory(zooList) { let zooFlat = []; let name = []; let animal = []; let age = []; for (let i = 0; i < zooList.length; i++) { if (!Array.isArray(zooList[i])) { name.push(zooList[i]) } else { animal.push(zooList[i][0]); age.push(zooList[i][-1]); } } for (let j = 0; j < name.length; j++) { zooFlat.push(`${name[j]} the ${animal[j]} is ${age[j]}.`) } return zooFlat; } zooInventory(myZoo); /* => ['King Kong the gorilla is 42.', 'Nemo the fish is 5.' 'Punxsutawney Phil the groundhog is 11.'] */Siguiendo mi comentario :
const myZoo = [ ['King Kong', ['gorilla', 42]], ['Nemo', ['fish', 5]], ['Punxsutawney Phil', ['groundhog', 11]], ]; function createSentence (item) { const [name, animal, age] = item.flat(); return `${name} the ${animal} is ${age}.`; } function zooInventory (zooList) { return zooList.map(createSentence); } console.log(zooInventory(myZoo));Su tarea es muy específica, por lo que optaría por una solución muy específica:
let myZoo = [ ['King Kong', ['gorilla', 42]], ['Nemo', ['fish', 5]], ['Punxsutawney Phil', ['groundhog', 11]] ]; function zooInventory(zooList) { return zooList.map(animal => animal[0] +' the '+ animal[1][0] +' is '+ animal[1][1] +'.') } console.log(zooInventory(myZoo))Como puede ver, no necesita hacer nada como aplanar si su asignación es exactamente esta, porque simplemente puede concatenar la lectura de cadenas de matrices anidadas.
... técnicas utilizadas ...
console.log([ ['King Kong', ['gorilla', 42]], ['Nemo', ['fish', 5]], ['Punxsutawney Phil', ['groundhog', 11]] ].map(arr => { const [name, animal, age] = arr.flat(); return `${ name } the ${ animal } is ${ age }`; })); .as-console-wrapper { min-height: 100%!important; top: 0; }