AnxiousdeV
AnxiousdeV

Reputation: 373

How to filter an array by an array in typescript and return result

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

Upvotes: 0

Views: 116

Answers (2)

dhaker
dhaker

Reputation: 1815

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

Upvotes: 1

Nick Vu
Nick Vu

Reputation: 15520

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

Upvotes: 0

Related Questions