Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

82
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda