0

I have a function that takes an array of dog objects and returns an array of the specific properties

The code that I have tried
function Owner(dogs) {
     dogs.map(value => {
     if (value.breed === 'GermanShepherd') {
         return value.owner;    
 }
}

1 Answer 1

2

One option is using reduce() and check if the breed if same with search variable, if it is, use concat() to add to the accumulator.

let arr = [{"name":"Beatrice","breed":"Lurcher","owner":"Tom"},{"name":"Max","breed":"GermanShepherd","owner":"Malcolm"},{"name":"Poppy","breed":"GermanShepherd","owner":"Vikram"}];
let search = 'GermanShepherd';

let result = arr.reduce((c, v) => v.breed === search ? c.concat(v.owner) : c, []);

console.log(result);


You can also use filter and map combo.

let arr = [{"name":"Beatrice","breed":"Lurcher","owner":"Tom"},{"name":"Max","breed":"GermanShepherd","owner":"Malcolm"},{"name":"Poppy","breed":"GermanShepherd","owner":"Vikram"}]
let search = 'GermanShepherd';

let result = arr.filter(o => o.breed === search).map(o => o.owner);

console.log(result);

Sign up to request clarification or add additional context in comments.

2 Comments

Happy to help :)
@Eddie Approach two is definetly are efficient and readable solution

Your Answer

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