Home > Mobile >  JavaScript function that takes a multidimensional array, flattens it, then returns array values as s
JavaScript function that takes a multidimensional array, flattens it, then returns array values as s

Time:03-26

Having trouble with a certain objective where I have to create a function that takes a multidimensional array and returns a flat array with sentence string values using values from the given multidimensional array. I'm having a hard time iterating through the array and getting it to push the values to a new array. Everything I've tried returns the values in the wrong spots and now it just returns undefined. I'm so lost and frustrated

Define a function, zooInventory, that accepts a multi-dimensional array of animal facts. zooInventory should return a new, flat array of strings. Each element in the new array should be a sentence about each of the animals in the zoo.

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.']
*/

CodePudding user response:

Following up on my comment:

TS Playground

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));

CodePudding user response:

Your assignment is very specific, so I would go for a very specific solution:

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))

As you can see, you don't need to do anything like flattening if your assignment is exactly this, because you can just concatenate the string reading from nested arrays.

CodePudding user response:

... techniques used ...

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; }

  • Related