Filter array of objects in Javascript

0

I have the following array of friends:

friends = [
  {id: 1, name: "uSUARIO2", username: "usuario1"},
  {id: 2, name: "uSUARIO2", username: "usuario1"},
  {id: 3, name: "uSUARIO3", username: "usuario1"},
  {id: 4, name: "uSUARIO4", username: "usuario1"}
];

And this array of followings

followings = [
  {id: 1, name: "uSUARIO1", username: "usuario1"},
  {id: 2, name: "uSUARIO2", username: "usuario1"},
];

I need to delete the elements from the array of friends that are equal to the following array, I have made several attempts but without success yet. For now I have:

filterFriendsFollowing() {
   let amigos_filtrados = this.friends.filter(
      (friend) => {
        for (let following of this.followings) {
          return following['id'] == friend['id'];
        }
    })
  }

How can I perform the filter correctly?

    
asked by CarMoreno 31.01.2018 в 01:12
source

2 answers

1
    filterFriendsFollowing() {
        let amigos_filtrados = this.friends.filter(friend=>{
           let res = this.followings.find((following)=>{
            return following.id == friend.id;
            });
         return res == undefined;
         });
      }

The filter () function is used in the friends array, that will allow you to create the desired array. Within the filter function, the find () function is used in the followings array. The find () function returns the first occurrence of the searched element, if it does not find it returns undefined, in this case, the condition will be following.id == friend.id; then, for the filter () function, the variable res is evaluated; if it is equal to undefined it means that the friend object was not found within the followings array and therefore fulfills the condition and is returned in the new array.

    
answered by 31.01.2018 / 01:30
source
1

I should filter when for each frying there is no corresponding following. Here I leave a snippet a little more optimal, I hope it serves you:

let friends = [
  {id: 1, name: "uSUARIO2", username: "usuario1"},
  {id: 2, name: "uSUARIO2", username: "usuario1"},
  {id: 3, name: "uSUARIO3", username: "usuario1"},
  {id: 4, name: "uSUARIO4", username: "usuario1"}
];

let followings = [
  {id: 1, name: "uSUARIO1", username: "usuario1"},
  {id: 2, name: "uSUARIO2", username: "usuario1"},
];

let amigos_filtrados = friends.filter(
  (friend) => {
    let ok = true;
    for (let i = 0; i < followings.length && ok; i++) { // Corta cuando no hay mas following o cuando ya se encontró uno
      let following = followings[i];
      if (following['id'] == friend['id'])
        ok = false;
    }
    return ok;
})

console.log(amigos_filtrados);
    
answered by 31.01.2018 в 01:27