1

Hi I am 99% there with the code below but I need this array of objects to return:- 'Bear', 'Minu', 'Basil', 'Hamish' instead it returns Bear,MinuBasil,Hamish any ideas?

    gatherPets([{ name: 'Malcolm', pets: ['Bear', 'Minu'] },{ name: 'Caroline', pets: ['Basil', 
    'Hamish'] },]);

    function gatherPets(people) {
      let newArray=[];
      for (let i=0; i <=people.length; i++ ) {
        newArray = newArray +people[i].pets
      }
      return (newArray)
    }

4 Answers 4

3

I hope this code helping you

array.flatMap(o=>o.pets)
Sign up to request clarification or add additional context in comments.

Comments

1

You could use the Array#flatMap method for this.

export function gatherPets(pople){
  return people.flatMap(p => p.pets);
}

1 Comment

Fantastic I love how efficient this is. Thank You
1

try this

gatherPets([{ name: 'Malcolm', pets: ['Bear', 'Minu'] },{ name: 'Caroline', pets: ['Basil', 
'Hamish'] },]);

function gatherPets(people) {
let newArray=[];
for (let i=0; i <people.length; i++ ){
newArray.push(...people[i].pets);    
}
return (newArray)
}

1 Comment

Thank you Maharajan thats perfect, I tried a push this way but it did not work when I tried it because I did not precede the people[i].pets with the ... What do the ... stand for?
0

You can use push() to push the values in the new array and flat() to flatten it.

function gatherPets(people) {
  let newArray = [];
  for (let i = 0; i < people.length; i++) {
    newArray.push(people[i].pets);
  }
  return newArray.flat();
}

const people = [{
  name: 'Malcolm',
  pets: ['Bear', 'Minu']
}, {
  name: 'Caroline',
  pets: ['Basil', 'Hamish']
}, ];

const result = gatherPets(people);
console.log(result);

Or you could simply use flatMap()

const people = [{
  name: 'Malcolm',
  pets: ['Bear', 'Minu']
}, {
  name: 'Caroline',
  pets: ['Basil', 'Hamish']
}, ];

const result = people.flatMap((p) => p.pets);
console.log(result);

1 Comment

Fantastic thank you the flatMap() method is super useful.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.