Home > Back-end >  javascript array filter callback with thisArg not working
javascript array filter callback with thisArg not working

Time:11-04

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'}))
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

You can not use an arrow function here since arrow functions inherit their this-context from the enclosing scope (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions). 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'}))
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related