0

I am struggling with returning an array of owner names from a given array of dog objects.

I know the reduce method is required in this instance, but I can't quite figure out how to proceed

function getPugOwners(dogs) {
  /*
    This function takes an array of dog objects and returns an array of the names of all the owners.
    E.g. [
      {name: 'Beatrice', breed: 'Lurcher', owner: 'Tom'},
      {name: 'Max', breed: 'Pug', owner: 'Izzi'},
      {name: 'Poppy', breed: 'Pug', owner: 'Anat'}
    ]
    will return ['Izzi', 'Anat']
    */
Jongware
  • 22,200
  • 8
  • 54
  • 100
Rowandinho
  • 193
  • 4
  • 14
  • `reduce` has nothing to do with what you want to achieve, anyway – Federico klez Culloca May 14 '19 at 12:40
  • 1
    Uh, the edit removes rather useful information. Right now the question is super unclear about what the data and the requirement is. – VLAZ May 14 '19 at 12:56
  • @FedericoklezCulloca to be fair, `reduce` can do it and it should be more performant than chaining `.filter` and `.map`. The latter are simpler to read to an extent but each will iterate the entire array *and* create a new array. A `reduce` is a common way to avoid the extra overhead of the eager evaluation in JS if you combine all the different operations in a `reduce`. – VLAZ May 14 '19 at 13:05
  • @VLAZ didn't think of that. Thanks for the heads up – Federico klez Culloca May 14 '19 at 13:09
  • @FedericoklezCulloca you can look into [transducers](https://medium.com/javascript-scene/transducers-efficient-data-processing-pipelines-in-javascript-7985330fe73d) if you are interested - in basic terms, they allow you to take a bunch of callbacks you would normally give to `filter`, `map`, and similar, but instead combine and run them with a single `reduce` operation. [And here is my favourite SO post about transducers](https://stackoverflow.com/questions/44198833/how-to-chain-map-and-filter-functions-in-the-correct-order/44211131#44211131) – VLAZ May 14 '19 at 13:26

3 Answers3

2

let dogs = [ 
{name: 'Beatrice', breed: 'Lurcher', owner: 'Tom'}, 
{name: 'Max', breed: 'Pug', owner: 'Izzi'}, 
{name: 'Poppy', breed: 'Pug', owner: 'Anat'} ];

function getPugOwners(dogs) { 
  return dogs.filter(dog => dog.breed=='Pug').map(dog => dog.owner);
}

console.log(getPugOwners(dogs));
PopHip
  • 700
  • 6
  • 23
1

you need to use 'map' method of Array

dogs.map(dog => dog.owner)

marsibarsi
  • 973
  • 7
  • 7
0

you can create function like this:

let dogs = [ 
{name: 'Beatrice', breed: 'Lurcher', owner: 'Tom'}, 
{name: 'Max', breed: 'Pug', owner: 'Izzi'}, 
{name: 'Poppy', breed: 'Pug', owner: 'Anat'} ];


function getOwnerByBreed(dogs,breed) { 
  return dogs.filter(dog => dog.breed==breed).map(dog => dog.owner);
}


console.log('Pug Owners',getOwnerByBreed(dogs,'Pug'));

console.log('Lurcher Owners',getOwnerByBreed(dogs,'Lurcher'));
Saurabh Mistry
  • 12,833
  • 5
  • 50
  • 71