Home > Back-end >  Filtering an array based on an Inner array
Filtering an array based on an Inner array

Time:09-20

I am trying to refactor my code in order to avoid doing new http requests to my api anytime I want to filter results.

So I have this array pageContent which gets data from an API fetch at page load. It is composed of several object like the one below:

{
"title": "some title",
"description": "some random description",
"tags": [
         "Tag1",
         "Tag2",
         "Tag3"
        ]
}

What I am trying to do is to filter this array if a certain filter button is clicked. This filter button emits a string as value that is then passed into the filter function. So this is what I have now:

this.pageContent.filter(element => {
  //ref is the string value that is emmited by the filter button
  return element.tags.includes(ref)
})

Unfortunately this is not working, and the array always shows exactly the same..

Any idea of what I am doing wrong?

Thank you!

CodePudding user response:

The issue is due to .filter returns a new array, it does not modify this.pageContent in-place. So:

this.pageContent = this.pageContent.filter(element => {
  //ref is the string value that is emmited by the filter button
  return element.tags.includes(ref)
})
  • Related