Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter Array within object using autocomplete

I am trying to filter on a array within a object based on a string using two filter methods. Here is what my object looks like.

[
  {
    "cat": "Accommodation and Food Service Activities",
    "value": [
      {
        "sic": "55",
        "desc": "Accommodation"
      },
      {
       "sic": "56",
        "desc": "Food and beverage service activities"
      }
    ]
  },
  {
    "cat": "Activities Of Extraterritorial Organisations and Bodies",
    "value": [
      {
       "sic": "99",
        "desc": "Activities of extraterritorial organisations and bodies"
      }
    ]
  }
] 

I am trying to filter on the value.desc and return the cat

Here is what I have so far

filteredIndustries(industry: string) {
    if (industry) {
      return this.industries.filter(sector => {
        if (sector.value) {
          sector.value.findIndex( v => {
            return v.desc.toString().toLowerCase().indexOf(industry.toString().toLowerCase()) === 0;
          });
        }
      });
    } else {
      return this.industries;
    }

and here is my html,

 <md-input-container>
      <input mdInput placeholder="Industry" [mdAutocomplete]="auto" [formControl]="industryCtrl">
    </md-input-container>

    <md-autocomplete #auto="mdAutocomplete" [displayWith]="displayIndustry.bind(this)">
      <md-option *ngFor="let industry of filteredIndustry | async" [value]="industry">
        {{ industry.cat }}
      </md-option>
    </md-autocomplete>

So when I enter food, it should filter on value.desc and return cat which should be Accommodation and Food Service Activities

But I am not getting any return value even though my return result is true.

Any help would be much appreciated.

like image 886
Ergun Avatar asked Sep 18 '26 07:09

Ergun


1 Answers

Your filter callback function misses a return statement, if findIndex returns something bigger than -1 you should return true;

filteredIndustries(industry: string) {
    if (industry) {
      return this.industries.filter(sector => {
        if (sector.value) {
          return -1 < sector.value.findIndex( v => { //HERE
            return v.desc.toString().toLowerCase().indexOf(industry.toString().toLowerCase()) === 0;
          });
        }
      });
    } else {
      return this.industries;
    }
}
like image 89
Pablo Lozano Avatar answered Sep 20 '26 22:09

Pablo Lozano