Finding precise matches between two arrays of elements

My data consists of two sets of arrays:

arr1 = [
         {id:1, children: ['a', 'b']},
         {id:2, children: ['a', 'b']},
         {id:3, children: ['b', 'c']},
         {id:4, children: ['c', 'a']},
         {id:5, children: ['a', 'b', 'c']}];

arr2 = ['a', 'b'];

I am looking to develop a JS/TS code that can accurately identify the objects in arr1 where every element in the children array matches exactly with every element in arr2's children array (regardless of order).

I attempted to address this issue using three filters and an additional condition for matching the lengths of the children arrays in arr1 and arr2. However, the current approach also captures cases where at least one element is matched from each children array despite the desired length.

I would greatly appreciate any assistance in solving this problem.

arr1
.filter(x => x.children
.filter(y => arr2
.filter(z => y === z)).length === arr2.length);

Edit:

This example simplifies my actual project. Here are the arrays I have:

 const orders: Order[] =
      [
        {
          productId: 1, subOrders:
            [{subProduct: {subProductId: 1}}, {subProduct: 
{subProductId: 2}}]
        },
        {
          productId: 1, subOrders:
            [{subProduct: {subProductId: 2}}, {subProduct: 
{subProductId: 1}}]
        },
        {
          productId: 1, subOrders:
            [{subProduct: {subProductId: 2}}, {subProduct: 
{subProductId: 3}}]
        },
        {
          productId: 1, subOrders:
            [{subProduct: {subProductId: 1}}, {subProduct: 
{subProductId: 2}}, {subProduct: {subProductId: 3}}]
        },
      ];

    const criteria: SubOrder[] =
      [
        [{subProduct: {subProductId: 1}}, {subProduct: {subProductId: 
2}}]

      ];

The goal is to identify products from the orders array where the subProductId in the subOrders array matches the subProductId in the criteria Array (Order doesn't matter). In this scenario, the first two products in the orders Array should match regardless of the order of subProductIds.

Answer №1

To solve the problem, one approach is to use a Set to compare and check if the children match a specific structure.

var array1 = [{ id: 1, children: ['a', 'b'] }, { id: 2, children: ['a', 'b'] }, { id: 3, children: ['b', 'c'] }, { id: 4, children: ['c', 'a'] },  { id: 5, children: ['a', 'b', 'c'] }],
    array2 = ['a', 'b'],
    set2 = new Set(array2),
    result = array1.filter(({ children }) =>
        children.length === set2.size && children.every(Set.prototype.has, set2));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

If dealing with a more intricate data structure, you can destructure the necessary elements and cross-reference them against a set of subProductId.

const
    getId = ({ subProduct: { subProductId } }) => subProductId;

var productOrders = [{ productId: 1, subProductOrders: [{ subProduct: { subProductId: 1 } }, { subProduct: { subProductId: 2 } }] }, { productId: 1, subProductOrders: [{ subProduct: { subProductId: 2 } }, { subProduct: { subProductId: 1 } }] }, { productId: 1, subProductOrders: [{ subProduct: { subProductId: 2 } }, { subProduct: { subProductId: 3 } }] }, { productId: 1, subProductOrders: [{ subProduct: { subProductId: 1 } }, { subProduct: { subProductId: 2 } }, { subProduct: { subProductId: 3 } }] }],
    matchingCriteria = [{ subProduct: { subProductId: 1 } }, { subProduct: { subProductId: 2 } }],
    set2 = new Set(matchingCriteria.map(getId)),
    result = productOrders.filter(({ subProductOrders }) =>
        subProductOrders.length === set2.size &&
        subProductOrders.every(o => set2.has(getId(o)))
    );

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

If you want to filter using both Array#every() and the length property, you can achieve that by combining them in a single filter operation.

const arr1 = [
   {id:1, children: ['a', 'b']},
   {id:2, children: ['a', 'b']},
   {id:3, children: ['b', 'c']},
   {id:4, children: ['c', 'a']},
   {id:5, children: ['a', 'b', 'c']}
];


const arr2 = ['a', 'b'];

const matched = arr1.filter(({children: c}) => c.length === arr2.length && arr2.every(v => c.includes(v)))

console.log(matched)

Answer №3

array1 = [
         {id:1, children: ['a', 'b']},
         {id:2, children: ['b', 'a']},
         {id:3, children: ['b', 'c']},
         {id:4, children: ['c', 'a']},
         {id:5, children: ['a', 'b', 'c']}];

array2 = ['a', 'b'];

const result = array1
  .map(item => item.children.sort())
  .filter(item => item.length === array2.length)
  .map(item => item.sort())
  .filter(item => JSON.stringify(item) == JSON.stringify(array2))

console.log(result)

Answer №4

When filtering the elements of array1, it's based on matching element.children with array2. I suggest checking out these responses as they delve into comparing two arrays in javascript.

Feel free to customize the following code to suit your requirements. Here is one simple option:

array1.filter((element,index) => {
      return JSON.stringify(element.children) === JSON.stringify(array2)
})

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

Accessing Headers in node request library

I need help retrieving the server response header for a request from a server. import 'request' from 'request' var url = "SOME_URL" var options = { url: url }; var callback = function(error, response, body) { if(!error){ ...

This code's workflow is completely confusing to me

Currently, I am engaging in an online tutorial that focuses on creating a basic web application using MEAN stack. The coding snippet provided below pertains to the modification of a collection of JSON objects (where videos are represented as JSON objects). ...

break LineSegment at specified location

Using the vertex positions provided below, I am creating a square using THREE.LineSegments (or even by a simple THREE.Line.) vertices: path.vertices = [ new THREE.Vector3( 3.4000015258789062, 0, 3.4000015258789062 ), new THREE.Vector3( 10.6000061 ...

Is there a way to connect a function to a div using anchor tags that mimic a dropdown menu?

Here is the HTML code for a navigation bar that I have created <div class="navbar"> <a href="#home">Home</a> <div class="dropdown"> <button class="dropbtn">Categories ...

What is the best way to invoke a controller method using jQuery within a cshtml file?

I am working on a project where I need to add user information to the database by calling a function in my controller class. The user's information is entered through a form created in a .cshtml file that interacts with an external JavaScript file. Is ...

Passing a particular method of a specific instance as an argument

I am interested in creating a class that allows me to specify "For instance a1 of A, you will call the function computeValue() of a specific instance b1 of B when the value is needed". It's important for me to indicate which method of which instance w ...

Issue encountered while adding an element to a numpy array in Python

I am trying to assign values to a 3D array that I have defined and initialized, but for some reason, the assignment is not working. Can anyone help me understand why? Thank you. import numpy as np xy = np.array([[(0,0) for _ in np.arange(0,2,0.5)] for _ i ...

What is the best way to access the onclick calling object?

Is there a way to have a handler on the calling object of the onclick event? <a href="123.com" onclick="click123(event);">link</a> <script> function click123(event) { //I need access to <a> in order to man ...

The Ajax PHP file uploader is experiencing technical difficulties

I am currently working on an ajax image uploader that is supposed to work automatically when a user submits an image. However, I've encountered an issue where the uploader does not function as expected when I try to rename the images for ordering purp ...

What could be causing my JavaScript pricing calculator to malfunction?

I've been struggling to make the script below work, but I can't seem to figure out why. It should be functioning properly. Even though all variables are in place, no price is appearing? You can view the HTML on this page: var cake_prices = n ...

There was an error stating that the operator for jsonb[] and integer does not exist

select data from entries where id=2; id | data ----+-------------------------------------- ...

Query the number of Firebase instances using the firebase.appCount property in Firebase v

When setting up Firebase in my React applications, I typically initialize it as follows: if (firebase.apps.length < 1) { firebase.initializeApp(firebaseConfig); // Additional initialization for other Firebase products } This method was working flaw ...

How can I connect an image to a link in Vue.js?

I am having trouble linking to another URL when I click on an image using Vue. It should be possible to link by clicking on the images, but it seems to not be working. If anyone can offer assistance, I would greatly appreciate it. Below is what my code ...

The asynchronous callbacks or promises executing independently of protractor/webdriver's knowledge

Could a log like this actually exist? 07-<...>.js ... Stacktrace: [31m[31mError: Failed expectation[31m [31m at [object Object].<anonymous> (...06-....js)[31m[31m[22m[39m It seems that something is failing in file -06- while I am processin ...

Why are the buttons on my HTML/JavaScript page not functioning properly?

I have been struggling with a code for a 5 image slideshow where the NEXT and PREVIOUS buttons are supposed to take me to the next and previous slides. However, when I press them, nothing happens. Can anyone provide some assistance? I need additional detai ...

Ensuring phone number accuracy through a custom validator along with JavaScript validation

My phoneTextBox control has 4 TextBoxes: country code (1-3 digits), city code (1-7 digits), local number (1-7 digits) and an optional extra phone number (1-5 digits). The provided code is not functioning correctly. <script type="text/javascript& ...

Creating a tooltip for new list items: A step-by-step guide

I'm currently working on creating a tooltip using JQuery for incoming list items. Users will input text in a textfield, press enter, and those values will be displayed in a visible list on the website. I intend to have a tooltip associated with each i ...

What is the best way to incorporate CSS from node_modules into Vite for production?

I have a TypeScript web application where I need to include CSS files from NPM dependencies in index.html. Here is an example of how it is done: <link rel="stylesheet" type="text/css" href="./node_modules/notyf/notyf.min.css&quo ...

Is there a way to replace a jquery function in the Chrome browser?

I am encountering an issue on a website where I usually take notes. Unfortunately, the right-click context menu has been disabled by the site administration. Despite my efforts to use a Chrome extension that can execute JavaScript on the page, I have not b ...

Transitioning the height of a Vue component when switching routes

I've been struggling to implement a transition slide effect on my hero section. The height of the hero is set to 100vh on the homepage and half of that on other pages. Despite trying various methods, I haven't been able to get it working properly ...