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

Comparing Redux with passing state down to components as props from the top level of the application

With limited experience in react-redux, I am currently working on a smaller web-based application intended for around 100 users. At this time, I have opted not to use redux due to concerns about its complexity for such a small project. Instead, I have been ...

Removing duplicate elements from an array using lodash

What is the best way to remove duplicate values from an array? var numbers = [1, 1, 5, 5, 4, 9]; I want my result to be: var numbers = [4, 9]; Is there a method in lodash that can help me achieve this? ...

Ways to verify user login through jQuery post method

I am currently working on a login test application that utilizes jQuery post and PHP. I'm encountering an issue where the application is able to read the input values but fails to send the data to server.php and consequently does not return any data. ...

Challenges with extracting and organizing dates using JavaScript regular expressions

My task involves organizing these text rows into specific groups based on certain criteria and names. Il Messaggero Roma 22 settembre 2023 Il Messaggero Roma 21 settembre 2023 Il Messaggero 22 settembre 2023 Il Messaggero 21 settembre 2023 Il Messaggero Ro ...

Transferring JSON data using DWR (Direct Web Remoting)

Utilizing DWR for AJAX calls in my project involves the conversion of JavaScript objects to Java objects by analyzing the Java class. My goal is to send and receive a JSON-like structure through DWR. For example: JavaScript Object: { "name" : "TamilVe ...

What is the reason for the regeneration of the 2D array?

I have a method called generateWeights() that retrieves random values in an array; And a method named learn() that calls the changeWeights() method to alter the values in the array. Expected: Prior to invoking the learn() method, I anticipate receiving an ...

Testing the functionality of an Angular service using unit tests

Confused about how to test a service in an Angular project that involves a small class with an observer? Can't seem to figure out why the test fails when calling the 'pop' method. Want to ensure that the public methods of this class perform ...

The getter method in the Vuex store object seems to be returning varying values when accessing nested properties

Currently, my Vuex store is being used to store a user object. This code snippet is a getter function for the user object: getters: { user: (state) => state, isAuthenticated: state => { console.log("user object", state); ...

REACT Issue: Unable to Select Dropdown Option with OnChange Function

I have a component that includes a select element. Upon clicking an option, the OnProductChange function returns the value. However, my e.target.value shows as [Object Object]. Yet, {console.log(product)} displays: {id: 1, name: "VAM"} Clicking on Add L ...

Error message: "Uncaught ReferenceError: $ is not defined in BackboneJS and RequireJS"

In my Backbone application, I am using RequireJS. However, I keep encountering the error message Uncaught ReferenceError: $ is not defined, indicating that my libraries may not be loading properly. This is what my RequireJS config looks like: require.con ...

Responsive left and right image styling in CSS and HTML

I have designed a landing page with fixed left and right images and content in the middle. It looks fine on desktop view, but on mobile view, the images are overlapping the content. How can I resolve this issue? <div class=" ...

Having trouble getting React app to recognize Sass properly

I have been working on developing a React app using TypeScript and the SASS preprocessor. Here is an example of my code: // Button.tsx import React from 'react'; import './Button.scss'; export default class Button extends React.Compone ...

The swap feature in drag-and-drop does not have a defined function

I am currently developing a to-do app that utilizes drag and drop functionality to reorder items in the list. However, I have encountered an issue where swapping elements works perfectly for the first five elements but throws errors when dealing with the s ...

Retrieving information from a PHP server using AJAX

Searching for a way to retrieve the posts created by users and load more posts upon user's request. Encountering an Unexpected end of JSON input error when initiating an ajax request in the console. Javascript $("#ajax_load_more").click(function ...

unresolved string constant issue with a django template command

I encountered an issue with the code snippet below, which is resulting in an unterminated string literal error: $(function() { $('#addDropdown').click(function() { var $d = $('{{ form |bootstrap }}').fadeIn(). ...

Issue encountered with the openpgpjs example: `'The function openpgp.encrypt is not defined'`

I encountered an issue with the 'openpgp.encrypt is not a function' error while attempting to follow the sample provided on the openpgp.js github page: https://github.com/openpgpjs/openpgpjs/blob/master/README.md#getting-started After following ...

Check the box to show the corresponding sections of the form

.If there are two checkboxes with options true or false, how should I handle a third checkbox? I want to display different parts of the form based on the selection of the checkboxes. ...

Is there a way to update JSON data through a post request without it getting added to the existing data?

Hello, I am currently delving into Angular2 and encountering a problem concerning RestAPI. When I send a post request to the server with a JSON file, I intend to update the existing data in the JSON file; however, what actually happens is that the new data ...

What could be the reason for my ajax request coming back with no data?

When I make this ajax request: $.ajax({ type: "POST", url: "/admin/RoutingIndicators/Add", data: { newSecondaryRI: newRi }, success: function () { alert('hit'); document.location.reload(true); }, error: fu ...

What is the process for sending a selected option using AJAX?

Using Ajax within Laravel to save data involves a form with input fields and a select option. Here is the form structure: <form class="forms" method="get" action=""> {{ csrf_field() }} <div class="form-group row ...