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 in Javascript to esxclude from an Array of Objects the items which contain specific pair of keys and values

I created this snippet to understand the issue

JSFiddle

I’m trying with a filter to exclude from an array all the items which have 2 specific keys as value === 'True' and team === 'Avengers'.

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

characters.filter(character => character.team !== 'Avengers' && character.value !== 'True');

My goal is to see as a result the following Object

[{
  name: "Flash",
  team: "Justice League",
  value: "False"
}, {
  name: "Deadpool",
  team: "X-Force",
  value: "False"
}]

As you see I should not see any item which has value === 'True' and also all the items which have team === 'Avengers'

But from the fiddles, you see that I’m having a wrong result and I don’t know how to fix this as there are 2 items that should be excluded because they have value === true but are not as you see below

[{
  name: "Flash",
  team: "Justice League",
  value: "False"
}, {
  name: "Deadpool",
  team: "X-Force",
  value: "False"
}, {
  name: "Deadpool",
  team: "X-Force",
  value: "true"
}, {
  name: "Deadpool",
  team: "X-Force",
  value: "true"
}]

>Solution :

String comparison is case-sensitive: a string that equals 'True' is not a string that equals 'true'.

You can fix this by including both in your filter condition:

character.team !== 'Avengers' && character.value !== 'True' && character.value !== 'true'

or (what I would probably do since it’s more durable) convert the string to upper-case before comparing for a case-insensitive comparison:

character.team.toUpperCase() !== 'AVENGERS' && character.value.toUpperCase() !== 'TRUE'

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