find all the possible combinations of elements from multiple arrays

I have a set of N arrays that contain objects with the same keys.

arr[
   {values:val1,names:someName},
   {values:val2,names:otherName},
]
arr2[
   {values:valx,names:someNamex},
   {values:valy,names:otherNamey},
]

My goal is to combine all possible combinations of objects from these arrays, resulting in a new array like this:

newArray[
{values:'val1''valx',names:'someName''someNamex'}
{values:'val1''valy',names:'someName''someNamey'}
{values:'val2''valx',names:'otherName''someNamex'}
{values:'val2''valy',names:'otherName''someNamey'}
]

I believe providing this detailed example will be helpful in solving this problem. Thank you for your attention!

Many thanks for your assistance!

Answer №1

Provided here is a potential approach to reach the desired goal.

Code Snippet

const myArray1 = [
   {values:'val1',names:'someName'},
   {values:'val2',names:'otherName'},
];
const myArray2 = [
   {values:'valx',names:'someNamex'},
   {values:'valy',names:'otherNamey'},
];

const arrayOfArrays = [...Array(5).keys()].map(x => (
  [...Array(3).keys()]
  .map(k => ({
    values: `val${x}${k}`,
    names: `someName${x}${k}`
  }))
));
//console.log(...arrayOfArrays);

const myConcatenation = (a, b, ...objs) => (
  objs.flatMap((obj) => ({
    values: `${a.values} ${b.values}`,
    names: `${a.names} ${b.names}`
  }))
);
const functionF = (a, b) => [].concat(...a.flatMap(d => b.flatMap(e => myConcatenation(d, e, []))));
const cartesianProduct = (a, b, ...c) => (b ? cartesianProduct(functionF(a, b), ...c) : a);

console.log(
  'test case with only 2 arrays: ', cartesianProduct(myArray1, myArray2), '\n\n\t******\n\n'
);
console.log(
  'test case with multiple arrays of objects: ',
  cartesianProduct(myArray1, myArray2, ...arrayOfArrays)
);
.as-console-wrapper { max-height: 100% !important; top: 0 }

Explanation

  • Based on the cartesian-product answer referenced by pilchard tailored for this scenario
  • Utilizes the cartesianProduct method for the given array sets
  • Employs .myConcat() to modify the concatenation result to include string concatenation of values and names per object

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

What is the best way to store the output of a function in a local variable?

In my Type Script code, I am looking to store the return value of a function in a local variable. The process is outlined below: getdetail1(store){ let Cust_id=this.sharedata.latus_lead.m_type let url="http:domain.com" console.lo ...

What is the best way to utilize AJAX in sending chosen files to a PHP script?

I currently have two forms set up. Form A includes fields for name, age, address, email, and a hidden text field that holds the names of images to be uploaded in form B. Form B allows users to browse and select their photos using an input type File. ...

The Art of Div Switching: Unveiling the Strategies

I have a question regarding my website. I have been working on it for some time now, but I have encountered a challenge that I am struggling to overcome. After much consideration, I am unsure of the best approach to take. The issue at hand is that I have ...

Issue encountered while conducting tests with Jest and React Testing Library on a React component containing an SVG: the type is not recognized in React.jsx

In my Next.js 12.1.4 project, I am using Typescript, React Testing Library, and SVGR for importing icons like this: import ChevronLeftIcon from './chevron-left.svg' The issue arises when running a test on a component that includes an SVG import, ...

Making a column in a Vue data grid return as a clickable button

My goal is to utilize vue.js grid to display multiple columns with calculated text values, along with a clickable column at the end that triggers a dynamic action based on a parameter (such as calling an API in Laravel). However, when I include the last c ...

Why is Puppeteer failing to download to the designated folder using "Page.setDownloadBehavior" in Windows?

When trying to download a file using Puppeteer, I found that the code works perfectly on a Mac OS machine but fails on a Windows machine. The code snippet I used is shown below: await page._client.send( 'Page.setDownloadBehavior', { beha ...

Replace the content within the iFrame completely

Is it possible to have a textarea where I can input HTML code and see a live preview of the webpage in an iframe as I type? For example, here is the code I'd like to write in the textarea: <!DOCTYPE html> <html> <head> ...

How long do route providers typically last?

When using standalone components, we have the ability to place services into route providers. I couldn't locate this information in the documentation - what is the lifespan of these service instances? Are they destroyed when the route becomes inacti ...

Display Vue component using a string input

Is there a solution to make this non-functioning example work, or is its usage illegal? Vue.component('hello', { template: '<span>Hello world!</span>' }) Vue.component('foo', { data(){ return { ...

Require assistance in getting a slider operational

Hello there! I could really use your assistance with this code. I have been trying to make it work using JavaScript, but I'm determined not to incorporate any external JS files. Here is the snippet of JavaScript code I am working with: "use strict"; ...

It appears that the Facebook share feature is not picking up any meta OG tags

There seems to be an issue with my Facebook share functionality as it's not reading any of the meta tags. It is indicating that the required properties such as og:url, og:type, og:title, og:image, og:description, and fb:app_id are missing. <script ...

Encountering a 400 (Bad Request) error while making a POST request to the server in a MERN

In my reactjs application, I added a button to delete user accounts. When the button is clicked, a form appears where users need to enter their password and click on Delete to confirm. However, when testing this feature, clicking on the Delete button does ...

Submit Button Field - HTML ButtonFor

Being relatively new to MVC Razor and web development, both front-end and back-end, I'm in need of a button that can send a stored value to the controller/model. I attempted to mimic the functionality of Html.TextBoxFor by giving it attributes similar ...

Tips for optimizing the processing speed of large XML files using jQuery, Javascript, and PHP

Currently, I am developing a store overview page that displays about 20 products per page. The data for this page is sourced from a zipped (gzip) XML file (*.xml.gz). You can find the feed here: . Every day, I download this file to my server using PHP and ...

Error 500: Issue with JQuery AJAX File Upload

Hey there, I'm facing an issue with doing a file upload using JQuery's AJAX feature as I keep getting the error 500. $(function() { $( 'form' ).submit ( function() { $.ajax({ type: &a ...

What is the best way to retrieve a FireStore document ID from an object?

I'm in the process of trying to reference an auto-generated firestore document ID in order to create a subcollection within it. The issue I'm facing is that although I can locate the document ID, I'm struggling to save it to a variable in a ...

Failing to catch the return value from a stored procedure in ASP Classic

Apologies for the lengthy post, but I wanted to provide all the necessary details. I am facing an issue with a JavaScript function that uses ajax to call some asp code, which then executes a stored procedure to check if a record already exists. Depending ...

Tips for validating form input upon submission in Angular 6

Within my Angular application, I have successfully implemented form validators. However, I am aiming to trigger form validation specifically upon submission. This means that when the user clicks on the submit button and the form is invalid, the errors indi ...

Creating a table from a PHP associative array

I've been attempting to organize an associative array in ascending order and then display it in an HTML table, but I've hit a roadblock with an error. I tried searching for solutions here on SO and followed the advice provided in some threads: P ...

Arrange a JSON response in descending order and filter out specific values

Currently, I'm encountering a challenge when trying to extract a specific attribute from my JSON response. The issue arises when I attempt to sort the results based on the `percentage_match` in descending order. Once sorted, my goal is to create an ar ...