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

Unable to Show the Contents of the Item - AngularJS

I'm in the process of developing an application that will showcase job details within a modal window based on the selected template. To achieve this, I've integrated ui.bootstrap and ui.router. However, I'm encountering difficulties in displ ...

Error: The Angular2 Router is unable to locate the XOutlet outlet in order to load the YComponent

I've encountered an issue while using named router outlets in Angular2 version 2.1.2. The error message I'm receiving is: Cannot find the outlet XOutlet to load 'YComponent' Although the error message is clear, I'm struggling ...

Currently, I am working on developing a to-do task manager using Angular 2. One of the tasks I am tackling involves updating the value

I'm facing an issue with managing to-do tasks. I would like to update the value of an option in a select dropdown when the (change) event is triggered. There are 2 components: //app.component.ts //array object this.dataArr[this.counter] = {id: this ...

Trying out asynchronous testing using Mocha and Sinonjs for the first time

In my current project, I am utilizing a custom micro framework developed by our team, where we make use of Mongoose. To handle the mongoose object, we have implemented a modelfactory that provides us with a corresponding model based on the mongoose name o ...

Using react-google-charts to create visually appealing dual-Y stacked bar charts

I am currently working on developing a bar chart with specific criteria in mind. My data follows the format: [month, region, totalSalesForCompanyA, totalSalesForCompanyB] I have successfully implemented the following charts: A dual-Y bar chart where mo ...

Transmitting an array within the POST request payload

My goal is to send an array to my Node/MongoDB server using an AJAX POST request, along with other variables in the body. Check out the client side JS code below: function setupForm(){ $("#add").submit(function(event) { event.preventDefault() ...

Angular: Tailoring the Context Menu

Currently, I am utilizing a helpful tutorial to implement a custom context menu feature. The main issue I am facing is that when a user interacts with the list items, I want the correct index of each item to be displayed. However, at the moment, clicking o ...

What could be causing Express to display a different page than the one specified in res.render?

Upon trying to view the compare.ejs page, I encountered an unexpected issue where a different page was being rendered instead. What could be causing this discrepancy? Here is my app.js code: var compare = require('./routes/compare')(nav); app.u ...

I encountered a "Bad Request" error when trying to login through my nodejs server, and I'm unsure of the reason behind this issue. As a beginner in nodejs, I'm still learning the ins and

passport.use(new LocalStrategy(async(email,password,done) => {    try{     const user = await User.findOne({email:email})     if(!user){        return done(null,false,{message:"Invalid email"})     }     const isValidPassword =aw ...

How to trigger a component programmatically in Angular 6

Whenever I hover over an <li> tag, I want to trigger a function that will execute a detailed component. findId(id:number){ console.log(id) } While this function is executing, it should send the id to the following component: export class ...

Deleting files with a dedicated function (Dropzone.js)

I need to implement functionality that removes the uploaded file when a 'cancel' button is clicked. Here's how my HTML code looks: <div reqdropzone="reqDropzoneConfig"> <form id="requisitionupload" class="dropzone dz-clickable" ac ...

Conceal the current component prior to displaying the component associated with Navlink in React Router

Currently, I am in the process of developing a single-page web application using React routing. My goal is to hide the current component before rendering the next component when a NavLink is clicked, similar to how <a href="someLink"> works in HTML. ...

Include a new key and its corresponding value to an already existing key within FormData

I have a form that includes fields for title, name, and description. My goal is to submit the form values using an API. To achieve this, I am utilizing jQuery to add key-value pairs to the FormData variable: formdata.append('description_text', jq ...

Vue 3: Leveraging Functions Within Mutations.js in Vuex Store to Enhance Functionality

In my mutations.js file, I have encountered a situation where one function is calling another function within the same file. Here's an example of my code: export default { async addQuestionAnswer(state, payload) { alert(payload); this.update ...

"Utilize Javascript to upload a picture and showcase it on your website

<!DOCTYPE html> <html> <head> <title>Unique Webpage!</title> <meta charset=utf-8 />                       <link rel="stylesheet" href="styles/customcss.css" /> <script src="j ...

Requiring three parameters, yet received four

Encountering an error in the dashboard.tsx file while trying to implement a line of code: "const { filteredEvents, stats, tableApps, formattedDate } = filterData(dataAll, Prefix, listApp, dateSelected);" The issue arose with the dateSelected parameter resu ...

Steps for instructing Google Maps to identify the location of a provided Google Maps URL

Is it possible to extract longitude and latitude data from a shared URL and place them into a marker? For example, users might copy and paste the 'Share' URL from Google Maps. For instance: or Direct Location: https://www.google.co.nz/maps/plac ...

Is it feasible to incorporate an Angular environment variable into an SCSS file?

I'm trying to come up with a solution for dynamically compiling my `scss` based on different environment profiles. Each location where my app will be installed has a different theme, but the CSS remains the same. The only thing that needs to change is ...

The Ubuntu virtual machine hosted on Google Cloud is experiencing difficulties connecting through Node.js using an external IP address

const express = require('express'); const bodyParser = require('body-parser'); const path = require('path'); const app = express(); app.listen(3000, function(){ console.log('Server is now live on port 3000' ...

Steps to display the Sidebar on top of the main information page

One unique feature of my website is the FiltersSideBar located on the left side of the page. It contains various filters to refine search results. To optimize user experience, I implemented a function that hides the sidebar at specific browser window size ...