I thought using bracket or dot notation with people.pets or people[pets] would return the results of the pets but not having luck.
This function will be called with an array of objects. Each object represents an owner and will have a pets property, which will be an array of pet names. The function should return an array of all the pets' names.
If passed an empty array the function should return an empty array.
A typical array of owners is shown below:
[
{
name: 'Malcolm',
pets: ['Bear', 'Minu'],
},
{
name: 'Caroline',
pets: ['Basil', 'Hamish'],
},
];
CodePudding user response:
That would be a perfect example for the use of the Array.reduce(). It would however keep duplicates names. Let's say if two owners had the same pet name, it would appear twice, so it depends on what you want.
const owners = [
{ name: "Malcolm", pets: ["Bear", "Minu"] },
{ name: "Caroline", pets: ["Basil", "Hamish"] },
];
const pets = owners.reduce((acc, item) => acc.concat(item.pets), []);
CodePudding user response:
This can do it, it prevents duplicates on pets names
let data = [{
name: 'Malcolm',
pets: ['Bear', 'Minu'],
}, {
name: 'Caroline',
pets: ['Basil', 'Hamish'],
}];
function getPets(data) {
if (!data) return [];
return Array.from(new Set(data.flatMap(e => e.pets)))
}
getPets(data)