'Returning an array of all the pet names

If I were to create a function, were a persons name was entered, how would I return an array with the names of the pets from the object below, what would be the best method if I were to use a for loop to iterate over it? I've not quite learnt some of the ES6 features yet and i'm new to coding.

A typical array of owners is shown below:

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

Thanks for the fast replies! :)



Solution 1:[1]

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

const petArray = (owner, ownersArray) => {
let array = ownersArray.filter((arr) => arr.name===owner)

  return array.length>0  ? array[0].pets : 'owner not found'

}
console.log(petArray("Caroline", ownersArray))

Solution 2:[2]

Try filter() method. The function returns an array of names from the filtered owner as a result.

Example code:

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

function petsNames(val) {
    return arr.filter(x => x.name === val)[0].pets;    
};

console.log(petsNames('Malcolm'));

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sumit Sharma
Solution 2