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

how can I filter array in object?

I would like to filter only people who have the color red as favColor… how can I do that?
this is what i tried: but not worked

const filteredpersonen = personen.filter(personen => personen.favColor= 'red');
console.log(filteredpersonen);

This is my code:

let personen = [
    {
      naam : 'jan',
      age : 41,
      favColor:[
        'blue',
        'green',
        'yellow',
        'orange'
      ]
    },
    {
      naam : 'james',
      age : 31,
      favColor:[
        'red',
        'black',
        'yellow',
        'purple'
      ]
    },
    {
      naam : 'linda',
      age : 21,
      favColor:[
        'blue',
        'white',
        'red',
        'grey'
      ]
    },
    {
      naam : 'marya',
      age : 31,
      favColor:[
        'creme',
        'green',
        'orange',
        'red'
      ]
    }
  ]

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

>Solution :

  1. = is assignment, == or === is comparison
  2. favColor is an array, so doing favColor === 'red' doesn’t make sense

Use .includes

const filteredpersonen = personen.filter(personen => personen.favColor.includes('red'));
console.log(filteredpersonen);
let personen = [{
    naam: 'jan',
    age: 41,
    favColor: [
      'blue',
      'green',
      'yellow',
      'orange'
    ]
  },
  {
    naam: 'james',
    age: 31,
    favColor: [
      'red',
      'black',
      'yellow',
      'purple'
    ]
  },
  {
    naam: 'linda',
    age: 21,
    favColor: [
      'blue',
      'white',
      'red',
      'grey'
    ]
  },
  {
    naam: 'marya',
    age: 31,
    favColor: [
      'creme',
      'green',
      'orange',
      'red'
    ]
  }
]

const filteredpersonen = personen.filter(personen => personen.favColor.includes('red'));
console.log(filteredpersonen);
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