Transform two sets of string arrays into nested objects

I have a challenge where I need to take two arrays (which are arrays of integers) and create nested objects using the "Cartesian Product" in both directions. I am considering whether this is more of a permutation problem and suspect that it may involve utilizing methods on the array prototype. Here's an example to illustrate:

const firstArray = [1, 2, 3];
const secondArray = [4, 5, 6];

function generateCartesianProduct(firstArray, secondArray) {
    // logic goes here
}

console.log(generateCartesianProduct(firstArray, secondArray))
// expected output
{
    "firstWay": {
        "1": {
            "4": true,
            "5": true,
            "6": true
        },
        "2": {
            "4": true,
            "5": true,
            "6": true
        },
        "3": {
            "4": true,
            "5": true,
            "6": true
        }
    },
    "secondWay": {
        "4": {
            "1": true,
            "2": true,
            "3": true
        },
        "5": {
            "1": true,
            "2": true,
            "3": true
        },
        "6": {
            "1": true,
            "2": true,
            "3": true
        }
    }
}

Answer №1

If you are looking for a solution, this code will definitely meet your needs. I hope this helps you achieve your desired outcome.

function createCartesianProduct(arr1, arr2) {
    var result = {};
    arr1.forEach(function(val1) {
        var temp = {};
        arr2.forEach(function(val2) {
            temp[val2] = true;
        });
        result[val1] = temp;
    });
    return result;
}

function calculateCartesianProduct(arr1, arr2) {
    var result = [];
    result['firstWay'] = createCartesianProduct(arr1, arr2);
    result['secondWay'] = createCartesianProduct(arr2, arr1);
    return result;
}

var arr1 = [1, 2, 3];
var arr2 = [4, 5, 6];

console.log(calculateCartesianProduct(arr1, arr2));

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

Using Object.defineProperty in a constructor has no effect

I recently revamped my three.js project and ran into a peculiar issue where all objects were being rendered with the same geometry and material. Upon further investigation in the debugger, I narrowed down the problem to this constructor: function Geometry ...

What is the best way to guarantee an Array filled with Strings?

Which is the proper way to define a potentially array of strings? Promise<Array<string>> Or Promise<string[]> ...

Variety of properties determined by a "type" prop, expanding variations based on a value from the interface

I am trying to enhance a type based on a value from the main interface. If the type == multiline, it will have a specific interface, and if the type == icon, it will have a different type. import React, { memo, useCallback, ReactNode } from 'react&apo ...

Can you use `keyof` to create a template literal type?

Defined a form schema type example: type FormSchema = { username: string; settings: { theme: string; language: string } } Now, trying to define the Form Input type like this: type FormInput = { id: keyof FormSchema | `${keyof FormSchema}.${string}` } Enc ...

Dealing with the state of an array of checkboxes: What you need to know

Is there a way to individually control the checked state of an array of checkboxes? Here is the array in question: const CheckboxItems = t => [ { checked: true, value: 'itemsCancelled', id: 'checkBoxItemsCancelled', ...

Naming convention for TypeScript accessors

Expanding on the previous solution When I convert the example object to JSON from the answer above: JSON.stringify(obj) The output is: {"_id":"3457"} If I intend to transmit this data over a service and store it in a database, I prefer not to use the ...

Excluding certain source files in Typescript's tsconfig is a common practice to

My attempt to configure Typescript to exclude specific files during compilation is not working as expected. Despite setting exclusions in my tsconfig.json file, the code from one of the excluded files (subClassA.ts) is still being included in the compiled ...

Error message in Vue3 with TypeScript: When using global components, you may encounter the error "JSX element type '___' does not have any construct or call signatures.ts(2604)."

Each globally registered component suddenly displays a red TypeScript squiggle in the markup! Surprisingly, the app continues to function without any visible errors! This issue arises with all components, whether they are custom-made or third-party libr ...

A TypeScript interface or class

Just had a lively discussion with a coworker and wanted to get some clarification. When shaping an object in TS, should we use a class or an interface? If I need to ensure that a function returns an object of a specific type, which one is the best choice? ...

Is there a way to adjust the width of a table cell in Material UI using React?

I encountered a problem where I am attempting to adjust the width of a table cell, specifically in Typescript. However, I am only able to choose between medium and small sizes for TableCellProps. Is there a workaround for this issue? I am looking to expand ...

What is the process for accessing my PayPal Sandbox account?

I'm having trouble logging into my SandBox Account since they updated the menu. The old steps mentioned in this post Can't login to paypal sandbox no longer seem to work. Could someone please provide me with detailed, step-by-step instructions o ...

Transform Material UI Typography to css-in-js with styled-components

Can Material UI elements be converted to styled-components? <Container component="main" maxWidth="XS"> <Typography component="h1" variant="h5"> Sign in </Typography> I attempted this for typography but noticed that t ...

Tips for implementing lazy loading for a section of a template in Angular 2

I have an Angular 2 component that has several sub-components within it. Some of these sub-components are expensive to load and may not always be necessary, especially if the user doesn't scroll far enough down the page. Although I am familiar with l ...

Transfer the current Angular project to operate as a separate entity

After successfully migrating my Angular project from version 13 to version 16 step by step, I am now aiming to make it fully standalone before proceeding with the migration to version 17. I am wondering if there is a utility available that can assist me i ...

Error message: When attempting to redirect to another route, there is a type error with 'this' as it is implicitly assigned the type 'any'

I'm facing an issue with a component I've built using hooks. I want it to redirect to a different route when a function is called and the server response is received. However, my TypeScript is throwing an error: Type error: 'this' impl ...

Encountering a NullInjectorError in Angular while utilizing dynamic module federation when importing a standalone component along with

My main goal is to develop a shell application acting as a dashboard without routing, featuring multiple cards with remote content (microfrontend standalone component). I have been following a tutorial that aligns closely with my requirements: . The reas ...

How can I pass additional props that are not specified in the interface while working with a React TS component?

I am working with a TS React component called MyButton.tsx: import React from 'react' interface MyButtonProps { children: JSX.Element | JSX.Element[], className?: string, variant?: 'big-button' | 'medium-button' | &apos ...

Alter the value by clicking a button within the DynamicRadioGroupModel in ng Dynamic Forms

I am working with ng-dynamic-form (version 6.0.4) and NG Bootstrap in Angular 6. I have a simple question. When a button click event is triggered, I want to change the value in DynamicRadioGroupModel by using the "setValue()" method. However, I am facing ...

Exploring React: A guide on looping through a dictionary within the render function using JSX

Currently learning React and working on a small test app where I'm making an Ajax call that returns a JSON object. I need to iterate over this object in the return method of my component. Despite trying various methods and searching online for answers ...

What could be the reason for the inconsistent behavior of onClick, causing it to occasionally fail to display the associated

I just started using typescript 2 days ago, mainly to create a custom component for my streamlit app. I've made a navigation bar with a tab that can be clicked on the sidebar, but it's displaying some erratic behavior. Sometimes when I click on t ...