Filter objects with criterion in the array within it

Asked

Viewed 61 times

4

Why am I not able to return only the objects containing the discipline Matemática?

I’m using the methods map() , filter() and, within the filter(), the includes(), but is returning all objects.

Can not use chained as I did, having to be triggered methods:

let dados = [
  {nome: 'Noah', disciplinas: ['Matemática', 'Geografia', 'Inglês']},
  {nome: 'Gael', disciplinas: ['Química', 'Geografia', 'Português']},
  {nome: 'Caleb', disciplinas: ['Matemática', 'Física', 'Artes']}
]

let discip = dados.filter(a => a.disciplinas.filter(b => b.includes('Matemática')))

console.log(discip)

1 answer

4


When you want to filter something, just do it once. It would only make sense if you wanted to have a filter inside the filter, but that’s not the case, you just want to filter people. Discipline is a criterion used is not another filter (as I understand it). So just take the list of subjects and see if the one you’re looking for is among those that the person has on their record, in a direct and simple way.

let dados = [
  {nome: 'Noah', disciplinas: ['Matemática', 'Geografia', 'Inglês']},
  {nome: 'Gael', disciplinas: ['Química', 'Geografia', 'Português']},
  {nome: 'Caleb', disciplinas: ['Matemática', 'Física', 'Artes']}
]

let discip = dados.filter(a => a.disciplinas.includes('Matemática'))

console.log(discip)

I put in the Github for future reference.

  • Right then, I understood Maniero, I really abused the method. Thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.