Determining the existence of a specific value within an array using JavaScript

I am looking at a JavaScript Array

business: [{
      "id": 22,
      "name": "Private",
      "max_mem": 0,
      "gen_roomtype_id": 4,
      "status": 1,
      "type": 0,
      "set_value": 1
    },
    {
      "id": 6,
      "name": "Standard ward",
      "max_mem": 0,
      "gen_roomtype_id": 2,
      "status": 1,
      "type": 0,
      "set_value": 1
    },
    {
      "id": 7,
      "name": "Semi Private",
      "max_mem": 0,
      "gen_roomtype_id": 3,
      "status": 1,
      "type": 0,
      "set_value": 1
    }],      

"gen": [{
      "id": 5,
      "name": "laboratory",
      "description": "",
      "sharing": 0,
      "set_value": 2
    }],

Now, I have an idArray like this

idArray: [5, 7]

I want to check if the values in the idArray belong to the "gen" Array or the "business" Array.

Answer №1

To check if all elements exist in an array, you can utilize the every function.

This method assumes that the provided data is in object format.

var obj = {  business: [{      "id": 5,      "name": "Private",      "max_mem": 0,      "gen_roomtype_id": 4,      "status": 1,      "type": 0,      "set_value": 1    },    {      "id": 6,      "name": "Standard ward",      "max_mem": 0,      "gen_roomtype_id": 2,      "status": 1,      "type": 0,      "set_value": 1    },    {      "id": 7,      "name": "Semi Private",      "max_mem": 0,      "gen_roomtype_id": 3,      "status": 1,      "type": 0,      "set_value": 1    }  ],  "gen": [{    "id": 5,    "name": "laboratory",    "description": "",    "sharing": 0,    "set_value": 2  }]
};

var idArray = [5, 7];

var resultBusiness = idArray.every(n => obj.business.some(b => b.id === n));
var resultGen = idArray.every(n => obj.gen.some(b => b.id === n));

console.log("All items in business: ", resultBusiness);
console.log("All items in Gen: ", resultGen);
.as-console-wrapper { max-height: 100% !important; top: 0; }

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

Finding the smallest value for each day in MongoDB using Mongoose

I have a collection in my MongoDB database called measured_data that includes entries for each day containing the fields measured_at and value. I am looking for a way to use Mongoose to find the lowest value recorded for each day. Any insights or suggest ...

What changes can I make to the script in order to display every element from a MySQL query using PHP, MySQL, JavaScript,

Enhanced Multiple Dropdown Selection Using Ajax In the following scenario, we have a webpage featuring a multiple dropdown selection that interacts with a MySQL database. By choosing options in the dropdowns labeled site, menu, and category (categ), a que ...

Using an image URL in a MongoDB database - a step-by-step guide

I am working on a cosmetics project website and need to create product information for each item. Each product will have an image, which I want to include by creating a URL for it and using EJS. For example, to display the image for a product, I would us ...

Client-side rendering for NextJS server components is also supported

I am currently working with Material UI v5.11.16 in a nextjs environment using v13.3.0. I followed the official documentation setup for my nextjs project which can be found here. So far, I have successfully integrated Material UI components without having ...

Updating the state in React can be achieved by using the `

Upon obtaining a list of search results, each result is equipped with an onclick function. My goal is to exhibit the user-selected results on the screen by adding them to an array upon click: let selectedData = [] function addFunc(resultdata){ consol ...

"Encountering an issue when trying to choose a value from a select list using jQuery and the

What am I missing here or what is the correct approach to solve this? Take a look at the following code snippet: code snippet $(document).ready(function() { $(".metric_div").hide(); $("#solid_radio").click(function() { $("#solid").show(); ...

What is the most straightforward method to access these four buttons?

Looking to create 4 interactive buttons with a unique behavior. When clicked, the chosen button will change its background image while the other 3 buttons retain their original background image unless hovered over by the user. Additionally, hovering over a ...

Connect a search function to a specific column in jQuery Datatables

Currently utilizing jQuery Data tables for a project. Looking to incorporate select boxes in one of the columns, with the actual cell value pre-selected. Is there a method to link a lookup table to this column, so each cell is connected to the lookup tab ...

JavaScript: Dynamic animation of a DIV element based on conditions

I am looking to create an animation for a DIV layer when another div is clicked. However, I only want the animation to play if the DIV layer has not been animated yet. My initial thought was to check the height value, as I am animating the height of the d ...

Avoiding the dreaded Pyramid of Doom in Angular by utilizing rxjs .subscribe to reduce the number of nested .subscribes

I've been diving into the wonders of RxJS's .merge lately, but I thought I'd throw my question out here too because the explanations are usually top-notch. So, here's the scenario: I have a form that triggers a modal window based on us ...

Error: Unable to locate module - Invalid generator instance detected. The Asset Modules Plugin has been started with a generator object that does not adhere to the API standards

Encountering an issue in nextjs when utilizing the 'asset/inline' Asset Module Type within a custom webpack configuration while running yarn dev. I attempted to utilize the 'asset/inline' asset module type to output the URI of the impor ...

The method piSession.buildPageInteractionSession is not valid

Hey there! I am facing an issue with a simple AJAX call to a PHP file. The request should be sent to the server and return back in an HTML input field. Unfortunately, I have not been able to resolve this error so far. Below is the code snippet: HTML: ...

Having trouble with AngularJs and moment.js integration?

Looking to create a simple webpage using Angular Js for date calculations. Utilizing moment.js from http://momentjs.com/ Below is the current code: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> ...

Event delegate failing to function correctly

When I click on the event button inside the template that is inserted after the current table row, the event works only once and then dies. The issue arises when you click on the newly added template with a .add class. $('.variations_grid tr td' ...

Obtain data from a post request using jquery

I need assistance retrieving posted data using jQuery. I have set up an HTML Form <form id="login_form" action="userPref.php" method="post" > <div hidden id="error" style="color:red; text-align:center;" > <p> user not fo ...

Delivering seamless css integration using express.js

Lately, I've been struggling with serving CSS using Express.js. After some trial and error, I managed to make it work. However, I'm puzzled as to why my new code works while the old one doesn't. Here's the code that now works for me: co ...

Retrieve the socket within a callback using socket.io

Currently, I am incorporating socket.io into my node.js project. When setting up an event handler like the example below: io = require('socket.io')(http); io.on('connect',function(socket){ socket.on('some event',function( ...

sending a counter variable from an HTML page back to a Node.js server

Beginner Node.js query.. My current server setup is as follows: var http = require('http'), fs = require('fs'); fs.readFile('./index.html', function (err, html) { if (err) { throw err; } htt ...

Ensuring your API server is always online: Tips and tricks

As part of my university assignment, I am developing a COVID-19 dashboard. Recently, the government decided to make COVID data publicly available in my country. Fortunately, I stumbled upon a NodeJS self-hosted RESTful API server endpoint that provides the ...

retrieving and presenting a specific JavaScript object using an index

var jsonData = [{ Fruit: "Oranges", Cost: 1.25 },{ Fruit: "Grapes", Cost: 3.10 }]; $('#addItem').click(function () { var chosenIndex = $('#fruitList option:selected').index(); I have a variable assigned to an index and I am t ...