angularangular-signals

Using computed signals for filter an array


I have an array which is assigned to a signal personList and im using a filteredPerson signal to display the number of persons after matching some filter criteria like search with textbox. We are planning to introduce another filter with queryParam ie while routing to the component with personList a default filtering with vehicles are to be made?vehicles=car.

In case of signals how should i approach new filtering logics as we go forward? Should the same computed() be used to write out other filtering methods(like age or gender)? If so then would that lead to a more messy code which will be hard to maintain on long run?.

Please advice on how to proceed. If there are any better alternatives other than queryParam please suggest as well.

let arr = [
 { "id": 1,"name": "sam","age": 43,"vehicle": "bike", "gender":"male" },
 { "id": 2, "name": "tom", "age": 23, "vehicle": "bike", "gender":"male"  },
 { "id": 3, "name": "alice", "age": 25, "vehicle": "car", "gender":"female"  },
 { "id": 4, "name": "bob", "age": 33, "vehicle": "car", "gender":"male"  },
 { "id": 5, "name": "xavi", "age": 46, "vehicle": "bike", "gender":"male"  },
 { "id": 6, "name": "pam", "age": 32, "vehicle": "car", "gender":"female"  }
];
    //Component starts here

searchItem:string = signal('');//Signal binded to search input
personList: WritableSignal<any[]> = signal(arr); 
filteredPersonItems: Signal<any[]> = computed(() => {
   const searchTerm = this.searchItem().toLowerCase();//Filter triggered during change of search item
   let filteredList = this.personList().filter(item =>item.name.toLowerCase().includes(searchTerm));
   return filteredList;
});



  //Template starts here
@for(person of filteredPerson();track $index;){
   <div>Name:{{person.name}}  Age{{person.age}}</div>
}


Solution

  • Do it in one computed Signal, cause you only have to run the filter on personList one time O(n). For clean code, you can outsource your filter functions.

    But, as example, you use for each new filter a new signal and then merge them together and take only these item which are in all computed lists, that gives you got O(n*FilterAmount+1).