Reem Obeid
Reem Obeid

Reputation: 85

Filter not working when filtering an array in an object

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

Upvotes: 0

Views: 941

Answers (3)

Zeeshan S.
Zeeshan S.

Reputation: 2091

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);

Upvotes: 1

froston
froston

Reputation: 1157

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
  }
}

Upvotes: 2

Shiva Sai
Shiva Sai

Reputation: 54

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);
}

Upvotes: 2

Related Questions