Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

86
Visualizações
javascript array filter callback with thisArg not working

According to the The Docs, the following is valid usage of filter with a callback AND an arg: filter(callbackFn, thisArg) Where 'thisArg' replaces the 'this' in the context of the callback. However, this does not seem to be the case, or I can not get it to be the case.

In this simple example I should be able to filter the array based on the tags. If I hard code a value inside the call back, it works but providing a tag via 'thisArg' nothing is returned and this.tag is undefined.

Thoughts?

musics = [
  {
    name: 'stinks like unwashed adolescent',
    tags: ['teen', 'energetic', 'excelent']
  },
  {
    name: 'After beethovens 4th',
    tags: ['older', 'moving', 'excelent']
  },
  {
    name: 'wap',
    tags: ['hip-hop', 'pounding', 'excelent']
  }
]

const filterTags = (element, index, arr) => {
   console.log(this.tag)
   return element.tags.includes(this.tag)
}
console.log(musics.filter(filterTags, {tag:'teen'}))

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You cannot use an arrow function here since arrow functions inherit their this-context from the enclosing scope.

Try this:

const musics = [
  {
    name: 'stinks like unwashed adolescent',
    tags: ['teen', 'energetic', 'excelent']
  },
  {
    name: 'After beethovens 4th',
    tags: ['older', 'moving', 'excelent']
  },
  {
    name: 'wap',
    tags: ['hip-hop', 'pounding', 'excelent']
  }
]

const filterTags = function(element, index, arr) {
   console.log(this.tag)
   return element.tags.includes(this.tag)
}

console.log(musics.filter(filterTags, {tag:'teen'}))

A functional approach using a closure:

const musics = [
  {
    name: 'stinks like unwashed adolescent',
    tags: ['teen', 'energetic', 'excelent']
  },
  {
    name: 'After beethovens 4th',
    tags: ['older', 'moving', 'excelent']
  },
  {
    name: 'wap',
    tags: ['hip-hop', 'pounding', 'excelent']
  }
]

const hasTag = tag => element => element.tags.includes(tag)

console.log(musics.filter(hasTag('teen')))

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda