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.