Reputation: 23
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'}))
Upvotes: 2
Views: 504
Reputation: 3496
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')))
Upvotes: 4