Home > Mobile >  How to filter an array by an array in typescript and return result
How to filter an array by an array in typescript and return result

Time:03-17

I am able to print the result, how would I return the result here to be assigned to an object

Attribute text is a string that we must split

this.childArrayAll.filter(x => x.attributeText1.split(",").forEach(y => {
    if(this.searchFilterForm.controls['types'].value.includes(y) )
        console.log(x);
}))

CodePudding user response:

Your idea is good, but you overuse array functions which makes it misunderstandable. And filter requires a true/false value, but forEach does not return that.

To make your logic simpler, I'd suggest you put an explicit logic for filter and return a proper true/false value based on your condition.

this.childArrayAll.filter(x => {
  const attributes = x.attributeText1.split(",")
  for(const attribute of attributes) {
    if(this.searchFilterForm.controls['types'].value.includes(attribute)) {
       //found matched attribute
       return true
    }
  }
  //no matched attributes
  return false
})

CodePudding user response:

You can use Array's some method to do it in clean and optimized way.

this.childArrayAll.filter(x => {
    const attributes = x.attributeText1.split(",");

    // Check if there is a match
    return attributes.some(attribute => this.searchFilterForm.controls['types'].value.includes(attribute));
});
  • Related