0

I'm trying to filter an array of strings

unfollow(handle: any) {
  let following = this.user?.following || [];
  following.filter((userHandle) => userHandle !== handle);
  console.log(following);
}

I want to filter the array of following in user object but when I console.log(following) the array is unchanged. I tried different things including this this.user?.following?.filter((userHandle) => userHandle !== handle); but nothing is filtered out

1
  • @froston A user is following 2 players this.user?.following = ["ronaldo", "messi"] then for example this user decides to unfollow("messi") so I simply want to update the array by filtering "messi" out Commented May 12, 2021 at 20:15

3 Answers 3

2

You need to assign filtered output to someother variable. Filter will return the new array which contains filtered result

unfollow(handle: any) {
  let following = this.user?.following || [];
 let newArray =  following.filter((userHandle) => userHandle !== handle);
  console.log(newArray);
}
Sign up to request clarification or add additional context in comments.

Comments

2

Array.filter returns a new array instead of mutating the existing one.

Try:

unfollow(handle: any) {
  let following = this.user?.following || [];
  let filtered = following.filter((userHandle) => userHandle !== handle);
  console.log(filtered);
}

or without the optional chaining:

unfollow(handle: any) {
  if (this.user) {
    let following = this.user.following || [];
    let filtered = following.filter((userHandle) => userHandle !== handle);
    this.user.following = filtered
  }
}

3 Comments

Yes this is what I'm missing, but now how can I update this.user?.following? If I try to do this this.user?.following = filtered I will get this error The left-hand side of an assignment expression may not be an optional property access.
That seems to be another issue. You would have to assign it to this.user.following avoiding the ? optional chaining operator.
Updated the answer according to your needs.
1

As per documentation for Array.prototype.filter(),

The filter() method creates a new array with all elements that pass the test implemented by the provided function.

Therefore, you need to store the output of the filter() to use it anywhere else, including console.log().

let filtered = following.filter((userHandle) => userHandle !== handle);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.