skip to Main Content
[
  {
    _id: "646231c54574e0e7ffc569e9",
    users: [
      {
        _id: "6461ef44496eff14402778af",
        name: "Salman Khan"
      },
      {
        _id: "6461f15bb4e0a6c7addc9fb0",
        name: "Yash Sharma"
      {
        _id: "646211fac7359b7ed8f27bcb",
        name: "abcd",
    ]
  }
]

I have an array with items like the above one. Now, I want to get that element which containes two specific _id in it’s users array.

2

Answers


  1. Start by semantically describing what you’re trying to accomplish:

    Array elements where:

    • the users array contains an element with an _id of X and,
    • the users array contains an element with an _id of Y and,
    • the users array contains no other elements

    Third condition added based on a comment above: "I’m looking for elements which only have two values not any other value."

    The description essentially defines the logic. For example:

    const arr = [
      {
        _id: "this one matches",
        users: [
          {
            _id: "6461ef44496eff14402778af",
            name: "Salman Khan"
          },
          {
            _id: "6461f15bb4e0a6c7addc9fb0",
            name: "Yash Sharma"
          }
        ]
      },
      {
        _id: "this one does not",
        users: [
          {
            _id: "6461ef44496eff14402778af",
            name: "Salman Khan"
          },
          {
            _id: "6461f15bb4e0a6c7addc9fb0",
            name: "Yash Sharma"
          },
          {
            _id: "646211fac7359b7ed8f27bcb",
            name: "abcd",
          }
        ]
      }
    ];
    
    const matches = arr.filter(a => 
      a.users.find(x => x._id === "6461ef44496eff14402778af") && // check for one ID
      a.users.find(x => x._id === "6461f15bb4e0a6c7addc9fb0") && // check for another ID
      a.users.length === 2 // make sure it has only those IDs (assuming they're unique)
    );
    
    console.log(matches);
    Login or Signup to reply.
  2. You can use filter method in combination with every element which will loop through your in put array and check if that is exists in each of the users array.

    const elements = [
      {
        _id: "646231c54574e0e7ffc569e9",
        users: [
          {
            _id: "6461ef44496eff14402778af",
            name: "Salman Khan"
          },
          {
            _id: "6461f15bb4e0a6c7addc9fb0",
            name: "Yash Sharma"
            },
          {
            _id: "646211fac7359b7ed8f27bcb",
            name: "abcd"
            }
        ]
      }
    ];
    
    const ids = ["6461ef44496eff14402778af", "6461f15bb4e0a6c7addc9fb0"];
    const result = elements.filter(elem => {
        return ids.every(id => elem.users.findIndex(e => e._id === id) > -1);
    });
    console.log(result);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search