0

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?

0

2 Answers 2

1

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()));
Sign up to request clarification or add additional context in comments.

2 Comments

Thnx @Alireza for your reply. push method is not working here actually but in second way it is working. it can be slightly reduced to- if (value.length > 0 ) { this.employees = this.employeeSearchArray.filter(v => v.employee_name.toLowerCase().includes(value.toLowerCase()) || v.employee_code.toLowerCase().includes(value.toLowerCase())); }
If you use *ngFor you're right push method does not trigger change action. I'm going to edit my answer. Thanks
0
 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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.