Return object values from multiple entries

Viewed 28

I've got some code there is handling an array of objects called into the function. I've got it to work mostly but when I call the function with a multiarray it doesn't return the expected values and just one of them.

Can you please fix the code and explain to me where I've gone wrong? Thank you!

function petPower(people) {
    let rest = people.reduce((a, b) => a && b.pets, []);
    return rest;
}

console.log(petPower([
    { name: 'Brain', pets: ['Doggy', 'Minuuy'] },
    { name: 'Carla', pets: ['Hammy', 'Hamishy'] },
  ]));

I want the above to return ['Doggy', 'Minuuy', 'Hammy', 'Hamishy'] but it's only returning Hammy and Hamishy.

3 Answers

You need to use Array.concat to append an array to another, not &&:

function petPower(people) {
    let rest = people.reduce((a, b) => a.concat(b.pets), []);
    return rest;
}

console.log(petPower([
    { name: 'Brain', pets: ['Doggy', 'Minuuy'] },
    { name: 'Carla', pets: ['Hammy', 'Hamishy'] },
  ]));

The answer provided by @Nick is correct and to answer why you were getting the output Hammy and Hamishy is because when your code reaches the last object it has a previous value of ['Doggy', 'Minuuy'] and the current value is ['Hammy', 'Hamishy']. The condition that is executed is ['Doggy', 'Minuuy'] && ['Hammy', 'Hamishy'] and since these are truthy values the last truthy value is returned which in your case is ['Hammy', 'Hamishy']

you can get vales like this with for in loop

and no need to mention exact keyfor access

const array = [
    { name: 'Brain', pets: ['Doggy', 'Minuuy'] },
    { name: 'Carla', pets: ['Hammy', 'Hamishy'] },
  ]

const getValues = (ar,temp)=>{
 const loopit = ar.map((e, i) => {
   for(x in e){
    if(Array.isArray(e[x])){
      temp.push(...e[x])
}
}})
return temp
}
console.log(getValues(array, []))

Related