2

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'}))

0

1 Answer 1

4

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')))

Sign up to request clarification or add additional context in comments.

1 Comment

This is the correct answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.