Verify whether an array in javascript consists of multiple values

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

I am working with an array structured like the example above. My goal is to extract the element that contains two specific _id values within its users array.

Answer №1

To begin, define the purpose of your task in a semantic manner:

Criteria for array elements:

  • the users array must include an element with an _id of X,
  • the users array must contain an element with an _id of Y, and
  • the users array should not have any other elements.

An additional condition based on feedback from a preceding comment: "I am searching for elements that only possess two specific values."

This explanation essentially outlines the logical process. For instance:

const arr = [
  {
    _id: "this one fits the criteria",
    users: [
      {
        _id: "6461ef44496eff14402778af",
        name: "Salman Khan"
      },
      {
        _id: "6461f15bb4e0a6c7addc9fb0",
        name: "Yash Sharma"
      }
    ]
  },
  {
    _id: "this one does not meet requirements",
    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") && // checking for first ID
  a.users.find(x => x._id === "6461f15bb4e0a6c7addc9fb0") && // validating second ID
  a.users.length === 2 // ensuring only those IDs are present (assuming uniqueness)
);

console.log(matches);

Answer №2

To check if each user in the input array exists in the users array, you can use a combination of the filter method and loop through each element.

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Steps to include a dynamic CSS class to a hyperlink within WordPress

Is there a way to apply an active CSS class to a link in Wordpress so that the active menu item will display a different color when the link is visited? <ul> <li class=""><a href="/news">News</a></li> <li class="dev ...

Exploring data elements in a Javascript array

Is there a way to use Javascript or jQuery to address the individual employee number, tasks, and sites in the following JSON array? $.each(mySchedule, function(i, obj) { console.log(obj.employees); }); var mySchedule = { "schedule": { "empl ...

Unveiling and Shifting Among Concealed HTML Forms

After going through numerous tickets with similar questions, I still can't seem to achieve what I want. So, I have no choice but to ask this question myself. I currently have an HTML page with 2 forms and 2 buttons. Both forms are initially hidden us ...

Tips for finding a duplicate button on a webpage with Protractor

After searching extensively, I am still struggling to find a way to locate a specific button on a webpage that lacks a unique identifier in the HTML. There are three buttons on the page, and the one I need to identify is the second one. Despite trying vari ...

Guide to duplicating a string into a two-dimensional array in the C programming language

I am looking to develop a C program that prompts the user to enter some words, for example: "example, input, in, programming." The program will then save these words into a string called "str" and proceed to dynamically create a 2D array to store the words ...

Technical issue encountered with radio button onchange/onclick event functionality

Is there a way to retrieve the value of a radio button when it is clicked or changed? I'm facing an issue where my code only works for the first radio button and not for the other ones. When I click on the first radio button, it alerts the value succe ...

Showing HTML element when the model count is zero - ASP.NET MVC View

My view has a dynamic element that switches between two options depending on the Model.Count property. Check out the code below: @if (Model.Count() == 0) { <div class="well well-lg"><h3>Everyone is present! No absences today :)</h3>& ...

Issues with padding in Bootstrap grid system

I'm currently working on a website using the bootstrap grid system. Although I have not used the row class, I am facing an issue with the padding between the divs. <div class="container"> <div class="col-lg-4"></div> <d ...

The React Click Counter Feature: Managing State Changes for a Single Element

I'm struggling with a seemingly simple task and need some help figuring it out. In my component, there are multiple buttons each with a "count" value set using state. When a user clicks on a button, the count increases. Currently, when I click on on ...

Technique for bypassing the requirement to initialize an array

When I need to allocate a zero-initialized array, my usual approach is: int size = 1000; int* i = (int*)calloc(sizeof(int), size)); Later in my code, I check if an element in the array has been initialized like this: if(!i[10]) { // i[10] has not been ...

Async/Await mishap

Could someone please explain why the code below is printing a blank result? I was expecting it to print "done" since I thought the await keyword would make the program wait for the promise to be resolved. Appreciate any help provided! let message = &apos ...

Identifying the position of an element as the first, nth, or last child within its parent using ReactJS

I'm currently experimenting with dynamic functionality in ReactJS and I need to determine the position of a child relative to its parent. How can I achieve this in ReactJS? I have come across this post which discusses detecting relationships between ...

issue with angular promise not resolving properly

In my current project, I am trying to ensure that a promise resolves after making a query on Firebase. The goal is to retrieve specific keys from one table and then iterate through another table to fetch the desired artwork. artistFactory.js 'use st ...

Utilizing URL Hashes to Integrate Isotope Filtering: A Comprehensive Guide

(Even though Wordpress is mentioned, I believe this problem is not specific to Wordpress) I am currently building my own website using Wordpress and the theme I'm using includes the Isotope by Metafizzy package. This package helps in filtering posts ...

I tried to use my Google Maps app, but for some reason, it failed

Here's the code snippet I've been working on: if($_POST){ // get latitude, longitude and formatted address $data_arr = geocode($_POST['address']); // if able to geocode the address if($data_arr){ $latitude = $data_arr[0]; $l ...

A guide on extracting the values of checked checkboxes by their ID using javascript

I'm currently attempting to extract the values of selected checkboxes. These checkboxes have distinct IDs because they are specified within a modal window. <input type = 'checkbox' id = 'audience_Name-$row[asset_ID]' value = &a ...

Avoid triggering child states in ui-router

Here is the progress I have made with ui-router states: $stateProvider .state('tools', { url: '/tools/:tool', template: '<div ui-view=""></div>', abstract: true, onEnter: function ($stateParams, ...

Is it possible to rebind data on a RadCombobox using ajax?

Recently, I've been restructuring my workflow by utilizing a webservice to help me better organize things. This has made using AJAX much simpler and efficient for me. Currently, when a user wants to save a new contact, they are added to a database th ...

Exploring a multidimensional PHP array---Navigate through a

Array ( [meta_data] => Array ( [5] => Array ( [id] => 33286 [key] => course_id [value] => FF2342 ) ) ) In order to retrieve the desired information, I cannot rely on using the ind ...

Error encountered: Module './charset.js' not found

What is causing this error to occur? Uncaught Error: Unable to locate module './charset.js' package.json { "name": "app", "version": "1.0.0", "description": "Application created with Flux and React.js", "main": "app.js", "scripts": { ...