The logic behind combining elements from two arrays in JavaScript/TypeScript

Explanation of two different array formats

const arr1 = [
  {
    "elementName": "one"
  },
  {
    "elementName": "two"
  }
]

const arr2 = [
  {
    "type": "RPT_PROPERTY_DEMOGRP",
    "values": [
      {
        "label": "HH"
      },
      {
        "label": "HH1"
      }
    ]
  },
  {
    "type": "RPT_PROPERTY_PLAYBACK_TYPE",
    "values": [
      {
        "label": "WW"
      },
      {
        "label": "WW1"
      }
    ]
  }
]

I am looking to create combinations from these two arrays such as:

  1. 'one HH WW'

    'one HH WW1'

    'one HH1 WW'

    'one HH1 WW1'

    'two HH WW'

    'two HH WW1'

    'two HH1 WW'

    'two HH1 WW1'

Any suggestions on how to implement this logic in JavaScript or TypeScript?

Answer №1

To tackle this problem, consider combining both iterative and recursive strategies.

const
    cartesian = (a, b) => a.reduce((r, v) => r.concat(b.map(w => [].concat(v, w))), []),
    arr1 = [{ elementName: "one" }, { elementName: "two" }]
    arr2 = [{ type: "RPT_PROPERTY_DEMOGRP", values: [{ label: "HH" }, { label: "HH1" }] }, { type: "RPT_PROPERTY_PLAYBACK_TYPE", values: [{ label: "WW" }, { label: "WW1" }] }],
    result = [
            arr1.map(({ elementName }) => elementName),
            ...arr2.map(({ values }) => values.map(({ label }) => label))
        ].reduce(cartesian);

console.log(result.map(a => a.join(' ')));
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

If you need to find a cartesian product, check out this resource:

const firstSet = array1.map(item => item.name);
const secondSet = array2.map(item => item.values.map(value => value.label));
const combinedData = [firstSet, ...secondSet];
combinedData.reduce((accumulator, set) => accumulator.map(x => set.map(y => [x, y].flatten())).flatten())

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

Learn how to use Javascript and ASP.NET to refresh the parent page in Mozilla Firefox browser

The code window.opener.location.reload(); works well in Internet Explorer, but it doesn't refresh the parent page in Mozilla Firefox. Can someone please advise me on how to refresh the parent page in a way that is cross-browser compatible? Here is th ...

I am facing an issue with Nestjs where it is unable to resolve my dependency, despite the fact that it is readily available within the

Encountering the following error: Error: Nest is unable to resolve dependencies of the CreateGroupTask (TaskQueueService, GroupsService, ?, GroupNotificationsService, GroupRepository, Logger). Please ensure that the argument dependency at index [2] is avai ...

My node.js and express application is encountering an issue where it is failing with an error indicating that a variable has not been

Currently in the process of understanding how node.js and express operate. I've successfully extracted data from my mongo database... and now I'm experimenting with transferring data between my router code and views. The locations.js file within ...

Using React to Filter cards according to the selected value from an Autocomplete feature

I'm currently developing a React application that utilizes Material-UI's Autocomplete component to filter cards based on selected car brands. These cards represent various models, and the goal is to update them when a user picks a brand from the ...

Turn off the chrome react DevTools when deploying to production to ensure the

I have successfully browserified my react app for production using gulp and envify to set up NODE_ENV. This has allowed me to remove react warnings, error reporting in the console, and even disable some features like the require of react-addons-perf. Afte ...

Ensure that the HTML input element only accepts positive values, including decimal numbers

I need to build an input field that only accepts positive numbers, including decimal values. Leading zeros are not allowed, and users should not be able to paste invalid values like -14.5 into the field. Here is my current implementation: <input type= ...

PWA JavaScript struggling with GPS geolocation coordinates

I am experiencing issues with the GPS coordinates being stuck when using geolocation in a Progressive Web App (PWA). Sometimes, the coordinates get stuck at the previous location, even if the user has moved since then. I suspect that this is due to the GP ...

Ways to implement a delay in a function?

I'm looking for a way to introduce a delay in my function. Should I enclose the function within a delay function, or is there a different method to ensure that the animation doesn't trigger until 5 seconds after the page has loaded? var textTo ...

ViewCheck and every

Can IsInView be set to wait for all elements with the same class, instead of calling them individually? For instance, if there are three sections, can they be called like this: $(".section").on('inview', function(event, isInView) { i ...

Not motivated to write HTML content

Recently, I've been utilizing the lazySizes plugin for optimizing my images. However, I encountered an issue when trying to implement it for HTML content display. Is there a simpler way to achieve this and maintain my current HTML structure? $(&apo ...

The type of link component that is passed in as the 'component' prop

I have created a custom Button Function Component in TypeScript using Material-UI as the base. After styling and adding features, I exported it as my own Button. Now, when I try to use this Button component in conjunction with the Link component from react ...

I encountered an issue in reactjs where I received the error message: TypeError: this.state.coords.map is not functioning properly

Here is the code snippet I wrote: import React, { Component } from 'react'; class LocationApp extends Component { constructor(props){ super(props) this.state = { coords:[], error:[], } } ...

How can we transfer a jQuery value from an input field without using a single

This task may seem challenging. How can single quotes be eliminated from a variable when passed directly to another variable? I am using jQuery variable $("#test").val() to extract the value from an input below <input type="text" ...

Ways to integrate a security protocol with a graphql resolver

I'm currently diving into the world of graphql and I'm facing a challenge with incorporating an authentication/authorization system into my project. I stumbled upon an example on Medium, but I'm struggling to grasp how a guard connects with ...

The process of updating JSON data based on changes triggered by DOM events such as drag and drop

One challenge I am facing involves a Vue component used to render child components based on JSON data. The goal is to allow users to move and add components by dragging and dropping DOM elements on the page, using tools like jQuery draggable, droppable, an ...

Integrating data between Java and JavaScript within the Wikitude platform is essential for leveraging AR.RelativeLocation

After passing an integer from Java to JavaScript, I am attempting to use the value to adjust the altitude of an object. I included the variable in RelativeLocation var location = new AR.RelativeLocation(null, 8, 0, a); The issue arises when it disregards ...

Using an ng-repeat directive alongside an if condition in Angular

My website contains a vast array of 30 articles, previously represented by around 300 lines of HTML code, but now condensed to just 10 lines with angularjs. However, certain articles hold special significance and require specific display criteria. Check ou ...

Unlock hidden Google secrets within your Angular application using Google Secret Manager

Can the Google Secret Manager API be accessed with a simple API call using an API key? https://secretmanager.googleapis.com/v1/projects/*/secrets/*?key=mykey returns a 401 unauthenticated error. While the Node.js server powering the Angular app uses the c ...

Is there a way to target a sibling element of another element by using its identifier in Cypress?

My current task involves clicking a checkbox within a list of table rows. The only way I can think of reaching this level is by targeting the span tag along with its corresponding name. cy.get('tr > td > span').contains('newCypressTes ...

Exploring Object Arrays with Underscore.js

Here is an array of objects that I am working with: var items = [ { id: 1, name: "Item 1", categories: [ { id: 1, name: "Item 1 - Category 1" }, { ...