skip to Main Content

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:

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))

2

Answers


  1. 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)
    }))
    
    Login or Signup to reply.
  2. Use map and filter:

    let 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',
        }]
      }
    ];
    
    let output = categories.map((category) => {
       let name = category.categoryName;
       let items = category.items.filter((category) => category.power > 50);
       return {name, items};
    });
    
    console.log(output);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search