filterangular10angular-arrays

Angular array filter is not working on a list of string


I have an array of string, and want to filter out a particular string after some operation. But, it seems I am doing something wrong there.

this.displayUser.followers.filter(userId=>userId !== this.loggedUser.userid);

Here, followers is an array of string -> string[] and upon some action (say, unfollow); I want to remove the logged user's id from the displayed user's followers list. However, this filter operation does not seem to work.

On the other hand I tried using splice which is working perfectly fine.

this.displayUser.followers.splice(
      this.displayUser.followers.findIndex(userId=>userId === this.loggedUser.userid)
 ,1);

I am unable to understand what am I doing wrong in the first approach?


Solution

  • Array.filter does not change the array it performs its action on, but returns a new array with values that passed the condition. In order to use .filter and have the result saved, you can do:

    this.displayUser.followers = this.displayUser.followers.filter((userId) => userId !== this.loggedUser.userid);
    

    This will remove all entries where userId === loggedUser.userid.

    .splice on the other hand manipulates the array it performs its actions on, hence you will immediately see the results as expected.