Search code examples
javascriptarraysjavascript-objects

From an array of objects, return key in new array


I've got an array of objects, and have to return the key puppies in a new array: This function takes an array of dogs in the format:

[
  {breed: 'Labrador', puppies: ['Fluffy', 'Doggo', 'Floof'] },
  {breed: 'Rottweiler', puppies: ['Biscuits', 'Mary'] }
]

It should return an array of all the puppies from all the dogs:

['Fluffy', 'Doggo', 'Floof', 'Biscuits', 'Mary']

This is my code so far:

function collectPuppies (dogs) {

    let solution=[];
    for(let i=0; i<dogs.length; i++){
      solution.push(dogs[i].puppies);
    }
    return solution;
  }

It adds the names to solution, but returning them in between [[ ]]:

Expected [ [ 'Spot', 'Spotless' ] ] to deeply equal [ 'Spot', 'Spotless' ]

I've seen my solution in this thread, so I believe I'm not too far but can't figure out what I'm doing wrong. Can anyone help me out? Thanks in advance.


Solution

  • In the array of objects, puppies is also an array. So you're adding an array to an array. Instead of:

    solution.push(dogs[i].puppies);
    

    You need to loop through the puppies array and add each puppy to the solution array individually. Rather than adding the 'puppies' field to the solution array, a second inner loop loops through the puppies array for each object and adds it to the solution array. The second inner loop can easily be done by calling forEach() on the puppies array. For example:

    dogs[i].puppies.forEach((puppy) => {solution.push(puppy)});
    

    Then the final function is:

    function collectPuppies (dogs) {
        let solution=[];
        for(let i=0; i<dogs.length; i++){
           dogs[i].puppies.forEach((puppy) => {solution.push(puppy)});
        }
        return solution;
    }