Exploring the intricacies of nested arrays

I am searching for a solution to compare arrays within arrays.

let small = [[1, 3], [2, 2], [2, 3], [3, 0]];

let large = [[1, 0], [1, 1], [2, 0], [2, 2], [2, 5], [3, 0], [3, 2]];

For instance, I would like to determine how many arrays in small are present in large. A function that takes the above arrays as arguments and returns 2, as [2, 2] and [3, 0] from small exist in large.

What is your approach to accomplish this task?

Answer №1

To simplify the comparison process, convert one of the arrays into a set of hashes and then filter the second array based on this set:

const small = [[1, 3], [2, 2], [2, 3], [3, 0]];

const large = [[1, 0], [1, 1], [2, 0], [2, 2], [2, 5], [3, 0], [3, 2]];

const containsCount = (arr1, arr2, hashFn) => {
  const arr1Hash = new Set(arr1.map(hashFn));
  
  return arr2.filter(s => arr1Hash.has(hashFn(s))).length;
}

const result = containsCount(small, large, ([a, b]) => `${a}-${b}`); 

console.log(result);

Answer №2

If you are looking for a solution, you may consider the following code snippet:

let small = [[1, 3], [2, 2], [2, 3], [3, 0]];
let large = [[1, 0], [1, 1], [2, 0], [2, 2], [2, 5], [3, 0], [3, 2]];

let z = zeta(small, large);
console.log(z);

function zeta(a, b) {
  let join = m => m.join();
  let x = a.map(join);
  let y = b.map(join);
  
  return x.reduce((n, m) => (y.indexOf(m)>0) ? ++n : n, 0);
}

Hope this helps you with your task!

Answer №3

Utilize the every and some methods to compare the arrays with each other.

If you desire an array containing the subarrays that match, employ the filter method:

let result = small.filter(arr => 
  large.some(otherArr =>
    otherArr.length === arr.length && otherArr.every((item, i) => item === arr[i])
  )
);

This code snippet filters out the subarray from small that has a matching subarray in large with the same length and elements/items.

Live Example:

let small = [[1, 3], [2, 2], [2, 3], [3, 0]];

let large = [[1, 0], [1, 1], [2, 0], [2, 2], [2, 5], [3, 0], [3, 2]];

let result = small.filter(arr => 
  large.some(otherArr =>
    otherArr.length === arr.length && otherArr.every((item, i) => item === arr[i])
  )
);

console.log(result);

If you just need a count, then utilize the reduce method instead of filter for counting the matched items (based on the fact that the numeric value of true is 1 and that of false is 0):

let count = small.reduce((counter, arr) => 
  counter + large.some(otherArr =>
    otherArr.length === arr.length && otherArr.every((item, i) => item === arr[i])
  )
, 0);

Live Example:

let small = [[1, 3], [2, 2], [2, 3], [3, 0]];

let large = [[1, 0], [1, 1], [2, 0], [2, 2], [2, 5], [3, 0], [3, 2]];

let count = small.reduce((counter, arr) =>
  counter + large.some(otherArr =>
    otherArr.length === arr.length && otherArr.every((item, i) => item === arr[i])
  )
, 0);

console.log(count);

Note: If the subarrays consist solely of numbers, you could simplify the code by using Array#toString instead of comparing each element and the length:

let result = small.filter(arr => large.some(otherArr => "" + otherArr === "" + arr));

This approach converts both arrays into strings and compares the two strings directly. It can be implemented with reduce as well.

Answer №4

Implement a nested map() function for comparing two arrays and finding matching elements using stringification.

let arrayA = [[1, 3], [2, 2], [2, 3], [3, 0]];
let arrayB = [[1, 0], [1, 1], [2, 0], [2, 2], [2, 5], [3, 0], [3, 2]];
var matches = [];
arrayA.map(function(itemA){
    arrayB.map(function(itemB){
        if(JSON.stringify(itemA) == JSON.stringify(itemB)){
            matches.push(itemA);
        }
    });
});
console.log(matches);

Answer №5

const smallArray = [[1, 3], [2, 2], [2, 3], [3, 0]];

const largeArray = [[1, 0], [1, 1], [2, 0], [2, 2], [2, 5], [3, 0], [3, 2]];


const largeArrayToString = largeArray.map(item => item.toString())
const matchingItemsFound = smallArray.filter(item => largeArrayToString.includes(item.toString()))

console.log(`Number of matches: ${matchingItemsFound.length}`)

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

Jquery Position behaving unexpectedly during initial invocation

My goal is to have the autocomplete menu open above the input box if there is not enough space below it. The code functions properly, except for the initial render. It consistently displays at the bottom in the following scenarios: 1. When starting a searc ...

Having difficulty interpreting the responseText

Currently experimenting with Redis Webdis Dart Here's my code snippet #import('dart:html'); #import('dart:json'); class ChatClient { XMLHttpRequest listener; int parsePosition = 0; void connect(){ this.listener = ne ...

Prevent Scrolling of Body Content within a Specified Div

In my current situation, I am dealing with a large number of divs (over 300) that are being used as part of an interactive background. The issue arises when viewing the page on mobile versus desktop – there are too many divs on desktop, causing excessive ...

Is there a messaging app that provides real-time updates for when messages are posted?

I am in the process of developing a messaging application. User1 sends out a message, and I want to display how long ago this message was posted to other users - for example, "Posted 9 min. ago", similar to what we see on sites like SO or Facebook. To ach ...

Converting dates to time in amCharts v3: A step-by-step guide

I am looking to exclusively show "6 AM" on my X AXIS, rather than displaying 2019-09-05 06:00:00 Please refer to my code sample at https://jsfiddle.net/uwtz3p4h/ Is it feasible to only display the time? I have searched through their documentation but co ...

Effective methods for importing components in VueJS 2.0

As a newcomer to VueJs, I have a question regarding the best practice for importing components in a Vue Template Project. I currently have some components that are used in multiple views. After downloading an admin template, I noticed that the samples alwa ...

Is there a way to retrieve arrays nested within an object in Vue or JavaScript?

In my Vue instance, I have a data object named items <script> export default { data() { return { selected: "", items: { item1: [{ selected: "", inputType: "", inputTarget: "" }], ...

Delete the JSON object stored in local storage and reconstruct the array from scratch

I've encountered an issue with deleting an item from LocalStorage...here's the JSON data stored in LocalStorage. { "1461569942024" : {"t_id":1461569942024,"t_build_val":"PreBuild1","t_project_val":"18"}, "1461570048166" : {"t_id":1461570048166 ...

DNN Unveils New "Exit Confirmation" Pop-up Feature When Clicking External Links

Greetings fellow beginners! I've been struggling to make some changes on our DNN site (Evoq 8.5) with no success so far. The issue at hand is that we have links throughout our entire website that follow this format: <a href="www.site.com" class="e ...

Is there a way to turn off Sequelize syncing?

I need assistance with my nodejs project where I am trying to establish a connection with mysql. The issue is that the connection is automatically creating tables based on the models defined, which is not what I want. How can I disable this automatic table ...

Delete the click event listener that was previously assigned by a different script

After extensive investigation using the Chrome developer tools, I have identified a click event listener that needs to be removed: https://i.sstatic.net/dnB3Q.png I successfully removed the listener using the developer tools. Further analysis revealed th ...

The process of loading the Facebook like script using $.getScript is causing an issue where the

How can I make the Facebook like button display properly on my HTML page? I have successfully loaded scripts and divs for Twitter, Google +1 buttons, but the Facebook like button script is not displaying the button. The alert shows that the script is exec ...

Iterating through two arrays simultaneously in Java using the foreach loop

Is it possible to achieve this in Java? I have a straightforward question: ArrayList<String> arr1 = new ArrayList<String>(); ArrayList<String> arr2 = new ArrayList<String>(); // Processing arrays, filling them with data for(Strin ...

In the event of a 404 error, simply direct the user to the pageNotFound before ultimately guiding them back

I'm developing a website with Node JS and I want to implement a feature where if the user attempts to navigate to a non-existent page, they are redirected to a "Page Not Found" message before being automatically taken back to the home page after a few ...

Is it possible for a dash in a GET variable name to cause issues with req.query in NodeJS Express?

I am currently developing a GET endpoint in Node.js using Express to handle the following variable: ?message-timestamp=2012-08-19+20%3A38%3A23 However, I am facing difficulty accessing it through req.query. Whenever I try to access req.query.message-time ...

External website's Sharepoint modal dialog

Recently, I've been working with a Microsoft Sharepoint 2010 installation and noticed that when I search for items using the integrated search feature, the results contain a javascript call like this: <a id="SRB_g_b60c4a68_5348_49ec_846c_b9d069d67 ...

Implementing an import statement in an Electron renderer script

After following the Electron typescript quick-start code structure by cloning the repo, everything worked fine. However, when attempting to split my code into multiple .ts files and import them into the renderer script, I encountered an issue. Upon adding ...

How can JavaScript automatically calculate the sum of various numbers entered into multiple input fields?

I would like to automatically add different numbers entered in multiple input fields using JavaScript. Is there a way to calculate the sum of numbers entered in various input fields using JavaScript? "The input field consists of n numbers..." and I am ut ...

Having trouble retrieving the ng-model value from input in the controller

I am new to Angularjs and I am working with a datepicker in Ionic. After selecting a date, the input field is correctly getting the value of the selected date. However, I am facing an issue when trying to access this value in the Controller using $scope. ...

The output in Javascript featured the term undefined

var counter = 0; var message = 'Join us for our Christmas Family Service on Sunday, December 19th at 11:45 am. Explore the true essence of Christmas at Bethany Evangelical Church.'; /* The text */ var speed = 50; /* The speed/duration of ...