Ashad peal
Ashad peal

Reputation: 73

Search on array of items by multiple filter

I got a list of employees like this from an api- 246

[{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, …]
[0 … 99]
0:
  employee_code: "10001338"
  employee_name: "ABC"
  staff_id: "1720"

In ts file, search by employee_name and employee_code BUT only employee_code working

getEmployees() {
  this._service.getAllEmployees().subscribe(res => {
    this.employees = res.data;
    this.employeeSearch();
  })
}

employeeSearch(): void {
  this.employeeSearchArray = [...this.employees];

    
  this.parentController
    .valueChanges
    .pipe(debounceTime(500))
    .subscribe((value: string) => {
       if (value.length > 0) {
         this.employees = this.employeeSearchArray.filter((v: 
    {employee_employee_name: string}) =>  v.employee_employee_name 
           ? 
  v.employee_employee_name.toLowerCase().includes(value.toLowerCase()) 
           : null);

    this.employees = this.employeeSearchArray.filter((v: {employee_code: string}) =>  
      v.employee_code ? v.employee_code.toLowerCase().includes(value.toLowerCase()) : 
    null);
       } else {
         this.employees = this.employeeSearchArray;
       }
    });
}

How can I search by both properties in this array?

Upvotes: 0

Views: 337

Answers (2)

Alireza Ahmadi
Alireza Ahmadi

Reputation: 9893

That's happen because you use assignment operator (=) in both case. First you searched by name and then you searched by code and assign the result (only code result) to employees. So you override the first search (search by name) history.

Try this one:

this.employees = this.employeeSearchArray.filter(
                   v => v.employee_name.toLowerCase().includes(value.toLowerCase()) ||  
                        v.employee_code.toLowerCase().includes(value.toLowerCase()));

Upvotes: 1

Meet
Meet

Reputation: 345

 handleFilter(value) {
       this.employees = this.employeeSearchArray.filter((s) => 
       s.employee_name.toLowerCase().indexOf(value.toLowerCase()) !== -1);
}

You can also use this using search by name and pass the value to the handleFilter function value parameter.

Upvotes: 0

Related Questions