Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Trying to return a filter() value from an array of objects based on conditionals

I’m trying to return only a part of my object as an array based on conditionals but I’m kinda stumped.

I have an array of objects and I want to return an array of names for each key : value they fit in.

I do get only the unique pairings but I’m returning the food key:value as well and all of it is still inside an object not a new array. Some insight would be greatly appreciated. Newer to coding.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const organizeNames = function (foods) {
 let foodNames = foods.filter((names) => {
  if (names.food === 'oranges') {
  return names.name;
 }
});

console.log(foodNames);
};
console.log(
  organizeNames([
   { name: 'Samuel', food: 'oranges' },
   { name: 'Victoria', food: 'pizza' },
   { name: 'Karim', food: 'pizza' },
   { name: 'Donald', food: 'pizza' },
  ])
 );

>Solution :

You’re really close here. What you need to incorporate is .map() to map your list of objects to a list of names. Your filter part works, partly by accident, so I’ve fixed it to be more correct (return names.food === 'oranges'), and then once you have your list of objects that match ‘oranges’ for their food, you map that filtered list into a list of names by doing .map(names => names.name)

const organizeNames = function (foods) {
  let foodNames = foods.filter((names) => {
    // only keep items whose .food property === 'oranges'
    return names.food === 'oranges'; // returns true or false
  }).map(names => {
    // map the filtered list of objects into a list of names by
    // returning just the object's .name property
    return names.name;
  });

  return foodNames;
};
console.log(
  organizeNames([
   { name: 'Samuel', food: 'oranges' },
   { name: 'Victoria', food: 'pizza' },
   { name: 'Karim', food: 'pizza' },
   { name: 'Donald', food: 'pizza' },
  ])
);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading