What is the most effective method for determining if a JavaScript array includes any of the elements from a separate array?

Regarding the question title, I have implemented the following:

Array.prototype.containsAny = function (otherArray) {
  for (let i = 0; i < otherArray.length; i++) 
     if (this.includes(otherArray[i])) 
       return true;

  return false;
};


let set1 =  [3, 5, 9];
let set2 = [4, 5];
set1.containsAny(set2);

Is there an alternative approach that may be more efficient?

Answer №1

If you want to check for elements that exist in two arrays, you can utilize the some and includes methods.

let array1 = [3, 5, 9];
let array2 = [4, 5];

function checkIntersection(array1, array2) {
  return array1.some(element => array2.includes(element));
}

console.log(checkIntersection(array1, array2));
console.log(checkIntersection(array1, [1, 2]));

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

Fetching JSON data from a Node.js server and displaying it in an Angular 6 application

Here is the code snippet from my app.js: app.get('/post', (req,res) =>{ let data = [{ userId: 10, id: 98, title: 'laboriosam dolor voluptates', body: 'doloremque ex facilis sit sint culpa{ userId: 10' ...

Creating a Mongoose schema with a predefined key variable

I am currently utilizing expressjs, mongodb, and mongoose. My goal is to update the counts object within the given schema: var UsersSchema = new Schema({ username: { type: String, required: true }, counts: { followers: { type: Number, default: 0 } ...

Can you explain how the functionality of setState operates within React in this specific situation?

I've been working on updating the state of an object in my array. I managed to get it done, but I'm a bit confused about how it works. toggleVisited = countryCode => { var countries = [ ...this.state.countries ]; var countryToChange = c ...

Pass a reply from a function to a route in expressjs

I'm currently working on a project where I need to retrieve JSON data from an API using an Express server in Node.js. However, I'm facing some confusion regarding how Node.js manages this process. In my code, I have both a function and a route de ...

What could be causing the Uncaught Error to persist even after using .catch()?

Check out this code snippet: function pause(ms:number) { return new Promise((resolve:any,reject:any) => setTimeout(resolve,ms)) } async function throwError(): Promise<void> { await pause(2000) console.log("error throw") throw new ...

What could be the reason for the requested parameter not updating as expected?

Currently, I am working on a Unity web request feature that involves sending the selected bet to the server. While the initial bet is successfully transmitted to the server, an error occurs when attempting to change the bet value. The error displayed is as ...

Experiencing a 400 error while transitioning from ajax to $http?

I am facing an issue while trying to make a GET request using $http instead of ajax. The call functions perfectly with ajax, but when attempting the same with $http, I encounter a 400 (Bad Request) error. I have referenced the Angular documentation and bel ...

What is the best way to identify a trio of items in an array whose combined total matches a specific target sum?

I am currently utilizing three loops to tackle this problem, but the complexity is O(n3). Is there a way to achieve this with a lower complexity level? Sharing a JS Fiddle code snippet for the three loops approach: var arr = [1, 2, 3, 4, 5, 6, 7, 8]; v ...

Issues with Pen Points and Groupings

After receiving json data, my goal is to populate a map with markers that will cluster together if they are located too closely. To achieve this, I am utilizing specific extensions for Markers and Clusters available at this link. I have written code that ...

Combine two entities to create a new entity that mirrors the structure of the first entity

Can someone assist me with a data structure issue? Here are the objects I am working with: const elements = { item1: {color: 'blue', name: 'Item One' }, item2: {color: 'green', name: 'Item Two' }, item3: {colo ...

Can you help me identify the issue with this line of code in C++: `int [] a = new int[size];`?

Just like the title implies, int [] a = new int[size]; keeps giving me an error message. I am still new to C++, so I need some assistance in adjusting the code provided above (which was a pseudo-code given in class) to create an array. Appreciate the hel ...

What is the best way to evaluate fields across arrays of objects?

I am facing a situation where I have two arrays of objects: ArrayList<Object> list1 and ArrayList<Object> list2. Here is a simplified example of the code: Class Object1 { String str1 = "example"; } Class Object2 { String str2 = "example"; } ...

A guide on reading multiple character arrays from a file using C++

The contents of the file "Athlete info.txt" are as follows: Peter Gab 2653 Kenya 127 Usain Bolt 6534 Jamaica 128 Bla Bla 2973 Bangladesh -1 Some Name 5182 India 129 I am trying to write code that will read each line in the file and store the data in d ...

The behavior of Ajax is resembling that of a GET method, even though its intended method

Greetings, I am currently facing an issue while coding in Javascript and PHP without using jQuery for Ajax. My aim is to upload a file over Ajax and process it in PHP. Here is the code snippet: index.html <html> <head> <title>PHP AJAX ...

R: Streamlined method for computing totals of multiple items multiplied together (works well with JAGS)

I am currently working on calculating cell probabilities in an array resulting from sums of products for a model to be executed in JAGS within R. In this scenario, an object can exist in one of 3 states. During each time interval, it has the option to eith ...

vb.net code to eliminate the initial item in an array

Is there a more straightforward method to accomplish this task besides creating a new array that is one element shorter? ...

Exploring the world of handling GET and POST parameters in Node.js with

As someone who is new to Node/Express, I've noticed that GET parameters can be captured using the following syntax: app.get('/log/:name', api.logfunc); For POST requests, it can be done like this: app.post('/log', ... (with for ...

I am trying to use getColumnCount() and getPhysicalNumberOfCells methods in my Selenium WebDriver script but they are not

Currently, I am dealing with .xlsx spreadsheets in Selenium using a combination of Selenium-2.53.1 jar and Apache poi-3.17 jars. However, when attempting to retrieve the total number of columns through methods like getColumnCount() and getPhysicalNumberO ...

The vanishing act of the Kendo Editor Custom Tool from the DOM

I'm currently working with a standard Kendo Window that contains a Kendo Editor within a modal window. I recently added a dropdownlist to the toolbar of the Kendo Editor for a customized functionality. The purpose of this custom dropdownlist is to ins ...

How can NodeJS users effectively incorporate OAuth client logic into their applications?

I am currently integrating OpenID/OAuth authorization into my project and leveraging the openid-client package to achieve this. Within this package, we initiate an openid client using the code snippet below: const { Issuer } = require('openid-client& ...