Home > Software design >  How do i filter an array inside of a array of objects
How do i filter an array inside of a array of objects

Time:07-30

I'm trying to filter each initialState where tags[0].number > 10 and tags[1].number < 20

const initialState = [{
    id: 1,
    name: 'Product A',
    image: 'pic-001.jpg',
    tags: [{
      id: 1,
      number: 12
    }, {
      id: 2,
      number: 10
    }],
  },
  {
    id: 2,
    name: 'Product B',
    image: 'pic-002.jpg',
    tags: [{
      id: 1,
      number: 0
    }, {
      id: 2,
      number: 102
    }]
  },
  {
    id: 3,
    name: 'Product C',
    image: 'pic-003.jpg',
    tags: [{
      id: 1,
      number: 1202
    }, {
      id: 2,
      number: 100
    }]
  }
]

console.log(initialState.filter(e => e.tags[0].number > 10))

initialState.filter(e => e.tags[0].number > 10) returns the wrong result.

How can I filter the array nested in an array of objects ?

CodePudding user response:

Try this out, and filter returns a new array

const filteredArr = arr.filter(obj => obj.tags[0].number > 10 && obj.tags[1].number < 20 )

CodePudding user response:

Array.filter() method always creates a new array of filtered elements based on the condition applied.

Live Demo :

// Input array
const initialState = [{
  id: 1,
  name: 'Product A',
  image: 'pic-001.jpg',
  tags: [{
    id: 1,
    number: 12
  }, {
    id: 2,
    number: 10
  }],
},{
  id: 2,
  name: 'Product B',
  image: 'pic-002.jpg',
  tags: [{
    id: 1,
    number: 0
  }, {
    id: 2,
    number: 102
  }]
},{
  id: 3,
  name: 'Product C',
  image: 'pic-003.jpg',
  tags: [{
    id: 1,
    number: 1202
  }, {
    id: 2,
    number: 100
  }]
}];

// Filtere data based on the condition.
const filteredData = initialState.filter(({ tags }) => tags[0].number > 10 && tags[1].number < 20);

// Output
console.log(filteredData);

CodePudding user response:

That works for me but

const initialState = [
{
  id:1 ,
  name: 'Product A', 
  image: 'pic-001.jpg', 
  tags:[{id:1 , number : 12}, 
        {id:2 , number : 10}]
},
{
  id:2 ,
  name: 'Product B', 
  image: 'pic-002.jpg', 
  tags: [{id:1 , number : 0}, 
         {id:2 , number : 102}]
},
{
  id:3 ,
  name: 'Product C', 
  image: 'pic-003.jpg', 
  tags: [{id:1 , number : 1202}, 
         {id:2 , number : 100}]
}]

//filter each initialState tags[0].number > 10
const filteredItems = initialState.filter(e => e.tags[0].number > 10 );
//filter each initialState tags[1].number < 20
const filteredItems2 = initialState.filter(e => e.tags[1].number < 20 );
//filter each initialState tags[0].number > 10 AND initialState tags[1].number < 20
const filteredItems3 = initialState.filter(e => e.tags[1].number < 20 && e.tags[0].number > 10 );


console.log(filteredItems3);

You only forgot a "}" in the initialState.

  • Related