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

Filter items in an array within an object array

I’m looking to filter an array of objects that is within an array of objects. E.g. items within the nested array are filtered out but not items of the outer most array.

Here is a sample input array:

categories = [{
  categoryName: 'Mammals',
  items: [{
    name: 'Dog',
    power: '52',
  },{
    name: 'Bear',
    power: '205',
  },{
    name: 'Mouse',
    power: '7',
  }]
},{
  categoryName: 'Reptiles',
  items: [{
    name: 'Alligator',
    power: '230',
  },{
    name: 'Turtle',
    power: '39',
  }]
}];  

Desired output: power greater than 50:

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

output = [{
  categoryName: 'Mammals',
  items: [{
    name: 'Dog',
    power: '52',
  },{
    name: 'Bear',
    power: '205',
  }]
},{
  categoryName: 'Reptiles',
  items: [{
    name: 'Alligator',
    power: '230',
  }]
}];  

I have attempted to use the filter function as such, but it outputs the full original array:

output = categories.filter((category) => category.items.power > 50)

I also tried using .some like this, same issue:

output = categories.filter((category) => category.items.some((item) => item.power > 50))

>Solution :

Use map() to iterate over the categories, then use filter() to filter the items in each category.

output = categories.map(cat => ({
    ...cat, 
    items: cat.items.filter(i => i.power > 50)
}))
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