Make sure to verify if all values are contained within an array by utilizing JavaScript or TypeScript

These are the two arrays I'm working with. My goal is to ensure that every value in ValuesToBeCheckArr is present in ActualArr. If any values are missing from ActualArr, the function should return 0 or false. Additionally, there is an operator variable that can have a value of either AND or OR. I have successfully implemented a solution for the OR operator but am struggling to come up with one for the AND operator.

ActualArr = [1,2,3,4,5,6,7,21,25,35,50,132];
ValuesToBeCheckArr = [2,3,50,132];
Operator = AND/OR

if(Operator == AND) {
   //check every value of ValuesToBeCheckArr should be in the ActualArr
} else if(Operator == OR) {
   //check at least one value of ValuesToBeCheckArr should be in the ActualArr
   const checkIncluded = (arr1, arr2) => arr1.some(item => arr2.includes(item));
   const isIncluded1 = checkIncluded(["1", "2"], ["3"]) // true
}

Answer №1

Using the Operator == AND

==> you can achieve this by utilizing Array#every in conjunction with Array#some as shown below

const ActualArr = [1,2,3,4,5,6,7,21,25,35,50,132];
const ValuesToBeCheckArr = [2,3,50,132];

const result = ValuesToBeCheckArr.every(v => ActualArr.some(a => v == a))
console.log(result);


The every() method evaluates whether all elements in the array satisfy the criteria specified by the provided function. It returns a Boolean value.

The some() method assesses if at least one element in the array meets the conditions set by the supplied function. It returns true if there is an element in the array for which the provided function returns true; otherwise, it returns false. The original array remains unchanged.

Answer №2

This code snippet demonstrates the functioning of a checkInclusion function that evaluates whether one array is included in another based on a specified operator.

function checkInclusion(actualArr,checkArr,operator){
 let isIncluded = operator === "AND"?
 actualArr.every(item=>checkArr.includes(item)):
 actualArr.some(item=>checkArr.includes(item))
 return isIncluded;
}


console.log(checkInclusion(["1", "2","3"], ["1","3"],"AND"));
console.log(checkInclusion(["1", "2","3"], ["1","3"],"OR"));

Answer №3

To convert the .some to .every, you must modify the code. This change will ensure that every element in the array meets the specified condition:

NewArr = [10,20,30,40,50,60,70,210,250,350,500,1320];
ValuesToBeCheckedArray = [20,30,500,1320];
Operator = AND/OR

if(Operator == AND) {
   //check whether all ValuesToBeCheckedArray elements are present in NewArr
   const checkAllIncluded = (arr1, arr2) => arr1.every(item => arr2.includes(item));
   const isIncludedNow = checkAllIncluded(ValuesToBeCheckedArray, NewArr)
} else if(Operator == OR) {
   //check if at least one value from the ValuesToBeCheckedArray is in NewArr
   const checkAnyIncluded = (arr1, arr2) => arr1.some(item => arr2.includes(item));
   const isPresent = checkAnyIncluded(["10", "20"], ["30"]) // true
}

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

TypeScript: Unable to fetch the property type from a different type

Currently, I'm using create-react-app with its TypeScript template. However, I encountered an issue while attempting to retrieve the type of the property 'pending' in 'GenericAsyncThunk', similar to how it's done in the redux- ...

Avoid an excessive number of XHR/AJAX requests when using the Facebook embedded iframe

I am facing an issue with a Bootstrap Carousel that contains multiple social embeds from Facebook, all of which have videos. The problem is evident on this simple jsfiddle due to the Facebook embed. If you visit this page: https://jsfiddle.net/1L95vqn4/, ...

What is the proper way to add a string to a TypeScript array?

When attempting to add a string to a TypeScript array, I am encountering an error stating 'cannot push to undefined'. Is this the correct approach, or should I be using the spread operator instead? api.ts const api: IConfigName = {name: "getKey ...

What is preventing Apollo from achieving full transformation?

I have been struggling with an issue involving Apollo mutation for the past 2 days. Whenever I call a mutation on Angular Apollo generated code and subscribe to it, the subscription never completes. I am expecting a result from the server, but nothing is ...

Issue encountered: Next.js version 14, Tesseract.js Error: Module not found .../.next/worker-script/node/index.js'

While working with nextjs 14 and trying to extract text from an image using the tesseract.js node module, I encountered an error where the module was not found. The specific error message I received is as follows: Error: Cannot find module '...(projec ...

What is the location where VueJS stores the cached component while utilizing keep-alive feature?

I am currently exploring where Vue stores the cached component data when a component is encapsulated in the keep-alive component. Despite checking local storage, cache storage, and session storage, I have not been able to locate anything definite. My suspi ...

What is the best way to retrieve local variables within a React function?

I keep encountering this issue where I get a TypeError saying that the property 'classList' cannot be read for an undefined value, and this error occurs even before the functions are executed. The specific line causing the error is slide[n].class ...

Creating image gallery with navigation arrows in JS/jQuery to loop through array of thumbnails

I am relatively new to working with arrays, and I have been exploring ways to use them in controlling the positions of thumbnails when navigating through a series of images using next or previous buttons. My goal is to make the thumbs loop seamlessly whene ...

on clicking GTM, obtain a different child element

My HTML code is structured as follows: <div onclick="location.href='https://ford-parts-accessories.myshopify.com/products/ash-cup-coin-holder-with-lighter-element?refSrc=6748959244479&amp;nosto=productpage-nosto-1-fallback-nosto-1';&q ...

Is there a way to verify an email address and transfer form data to a different HTML page for printing?

How do I troubleshoot email validity checking issues in my form? It works fine when no characters are entered, but fails when characters are inputted. What could be causing this problem? Additionally, I want to open a new HTML sub-file after form submissi ...

Defining types for functions that retrieve values with a specified default

My method aims to fetch a value asynchronously and return it, providing a default value if the value does not exist. async get(key: string, def_value?: any): Promise<any> { const v = await redisInstance.get(key); return v ? v : def_value; } W ...

Issue with integrating the jquery tokeniput plugin in asp.net mvc 3

Having trouble integrating the jQuery Tokeninput plugin into my MVC application. Something seems off with the setup... The Code I'm Using: <input type="text" id="MajorsIds" name="MajorsIds" /> <script type="text/jav ...

Incorporate a "Back" button following the removal of the navigation bar in a Meteor-Ionic

When working on a Meteor-Angular-ionic app, I encountered a situation where I needed to hide the nav-bar in a template to create a full-screen view using the following code: <ion-view hide-nav-bar="true"> However, I then faced the challenge of addi ...

The combination of NextJS and Firebase Auth using the GoogleAuthProvider is powerful

I am encountering challenges while trying to integrate firebase authentication with Google Provider in NextJS. I have set up the necessary environment variables and successfully established a connection with firebase. However, I keep running into an error ...

I am curious to see the number of people who have made their selection

I am currently using JavaScript to alter the text value from "select" to "selected". My next step is to include the selected text in a cart. Can you please provide some guidance? Thank you in advance. PHP CODE : <a class='btn slct' href=&ap ...

Bizarre actions with jQuery append in Internet Explorer 8

Issue with adding elements to a div in IE8: The element is not added until the button is clicked twice, resulting in two new elements being added at once. Here's the code snippet in question: $(options.addButton).click(function(event) { var proto ...

Utilizing cloud functions to distort an inappropriate image

I have a requirement to analyze any uploaded image for inappropriate content and blur it if necessary. The log this image is inappropriate indicates that the detection process is working correctly. However, I am not able to see any further logs which sugg ...

Implementing specific CSS styles for different routes in Angular 5: Use Bootstrap CSS exclusively for admin routes

I am looking to apply Bootstrap CSS only to routes starting with '/admin'. I have enabled lazy loading for both admin and public modules. ...

HighCharts velocity gauge inquiry

I recently integrated a highcharts speedometer with PHP and MYSQL on my website. Everything seemed to be working smoothly until I added the JavaScript code for the speedometer, causing it not to display. There are no error messages, just a blank screen whe ...

Switching classes in jQuery for Internet Explorer 8

I am attempting to update the color of a header when it reaches a certain scroll position. I have implemented this script using jQuery: var $document = jQuery(document), $element = jQuery('#header'), className = 'red'; $docume ...