"Utilizing Javascript to create a matrix from a pair of object arrays

Attempting to transform an infinite number of arrays of objects into a matrix.

height: [1,3,4,5,6,7]
weight: [23,30,40,50,90,100]

to

1 23
1 30
1 40
1 50
...
3 23
3 30
3 40
...

Essentially mapping out all possible combinations into a matrix

I experimented with solving the issue using various functions in underscore.js

                var firstOption = _.first( productOptionKeys );
                $.each( productOptions[ firstOption ].split(","), function(index, value){
                    var matrixRow = [];
                    var matricableOptionKeys = _.reject( productOptionKeys, function(option){ return (option == firstOption); }  );

                    matrixRow.push( value );

                    $.each( matricableOptionKeys, function( index, value ){
                        var matricableOptions = productOptions[ value ].split(",");
                        var matricIndex = 0;
                        for( i=0 ; i<matricableOptions.length; i++ ){
                            matrixRow.push( matricableOptions[ matricIndex ] );
                        }

                        //matricIndex ++;
//                      $.each( productOptions[ value ].split(","), function(index, value){
//                          matrixRow.push( value );
//                          return false;
//                      });
                    });

                    console.log( matrixRow );
                });

The object is a bit more complex in my scenario as I need to split the entered string values into an array. However, for simplicity in finding a solution, I omitted that these values are comma-separated strings.

This question is unique as it aims to get all permutations of an object like the one below

Object { Height: "23,45,190,800", Width: "11",14",15",20"", Color: "Red,Green,Blue" }

Current solutions only cover permutations for arrays, not for objects. The values for each key will always be separated by commas, so `object[key].split(",")` will provide the values as an array.

If it were feasible to concatenate arguments for function calls, one of the existing functions could have been utilized.

Answer №1

Yes, certainly! One method to achieve this is by implementing a double for loop:

var result = [];
for(var i=0; i<height.length; i++)
    for(var j=0; j<weight.length; j++)
        result.push({ height: height[i], weight: weight[j]});

Once the loop finishes, the array named result will store all possible combinations of both height and weight.

Alternatively, you could use the forEach method of an array like this:

var result = [];
height.forEach(function(h){
    weight.forEach(function(w){
         result.push({ height: h, weight: w});    
    });
});

Answer №2

give this a shot

let size = [2,4,6,8,10];
let color = ['red', 'blue', 'green', 'yellow'];
let result = [];

for(s = 0; s < size.length; s++) {
  for(c = 0; c < color.length; c++) {
    result.push({s: size[s], c: color[c]});
  }
}

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

ng-show and ng-hide toggling for the active row

I have a single table where I am implementing row hide and show functionality using Angular for editing and saving purposes. So far, everything works as expected. $scope.init=function(){ $scope.editable=true; } Now, when I click on the edit button ...

Issue with setting an array using componentsSeperatedByString in Objective-C

My data source consists of around 2000 lines that have a similar format to the example below: 6712,Anaktuvuk Pass Airport,Anaktuvuk Pass,United States,AKP,PAKP,68.1336,-151.743,2103,-9,A My goal is to extract the 6th section of this string and convert it ...

There seems to be an issue with React-hook-form and material-ui not retaining value changes in the onBlur() method

Stepping into the realm of react-hook-form is a new experience for me. I'm putting in effort to grasp everything, but there are still some pieces missing from the puzzle. Seeking assistance akin to Obiwan Kenobi! The Dilemma at Hand: An <Textfiel ...

Error in React JS: SyntaxError - "Unexpected token '?'"

Following the guidelines on this website, I successfully set up a new reactJS application, proceeded to run npm i && npm run dev and encountered the following error message: /home/www/node_modules/next/dist/cli/next-dev.js:362 showAll ...

Error Encountered When Running JavaScript Code

Running the code on my Localhost:3000 is resulting in an error message: Unhandled Runtime Error TypeError: Cannot read properties of undefined (reading 'id') The specific section of the code causing this error is highlighted in the Source part: ...

Instructions on merging elements in an array with identical property values

Consider the array below: [{a:1,b:1},{a:5,b:2},{a:10,b:2},{a:20,b:3}] Is there a way to create a new array that merges elements with the same b value, while adding up the corresponding a values? The desired output should be as follows: [{a:1,b:1},{a:(5+10 ...

Load a JSON file into the app.js of your project

Could someone please help me figure out how to successfully load a JSON file into my project's app.js? I've tried using the following code snippet: var j = require('./JSON1'); However, it didn't work as expected. My goal is to la ...

Animate failed due to the appending and adding of class

$('#clickMe').click(function() { $('#ticketsDemosss').append($('<li>').text('my li goes here')).addClass('fadeIn'); }); <link href="http://s.mlcdn.co/animate.css" rel="stylesheet"/> <script ...

Creating sophisticated TypeScript AngularJS directive

Recently, I came across a directive for selecting objects from checkboxes which can be found at this link: The issue I'm facing is that we are using TypeScript and I am unsure of how to implement the directive in TypeScript. From what I understand, ...

Terminal throws an error stating that no default engine was specified and no extension was provided

I have been working on executing a backend program in Node.js using MongoDB. I have created a form with two input fields for password and name. I am not utilizing any HBS or EJS and my VS Code terminal is displaying the following error: No default engine ...

Targeting props within a Class Component: A Step-by-Step Guide

I am currently working on a MultiStep Form project. On the final page of the form, my goal is to push all the collected data to Firebase. I have been utilizing props and states to pass values from one page to another. However, I'm facing an issue in t ...

Utilizing the Loess npm module in conjunction with Angular 4

I am attempting to incorporate the Loess package into my project. The package can be found on NPM and offers various regression models for data fitting. I successfully installed it using npm install loess --save, and it now resides in the node_modules dire ...

Express JS encountering Firebase Google Sign-In glitch

Whenever a user clicks a button on the HTML page, this function is triggered. The function resides in auth.js and it is called from the server.js page. auth.js const firebase = require("firebase"); static googleSignIn(req,res){ firebase.aut ...

Issue with form validation, code malfunctioning

I am struggling to figure out why this validation isn't working. Here is the HTML code I'm using: <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script type='text/javascript' src="scripts. ...

Incorporating a new method into the Object prototype to provide universal access across all modules

I've been delving into Typescript experimentation and I'm attempting to enhance the Object prototype by adding a property that can be accessed by all objects within my modules. Here's what I've developed so far: In a Common.ts file O ...

When a timeout is triggered, the AngularJS Promise is not being cancelled

In my endeavor to incorporate a simple timeout feature into my promise, I set out with the intention that if I do not receive a response within 1 second, the request should be terminated. The code should not hang for a response nor execute any code intende ...

``Unresolved issue: Sending emails using Sendgrid and Firebase not working in production through Netlify

For a simple contact form, I am utilizing Nuxt, Sendgrid, and Firebase. Netlify is being used for hosting the project. The contact form works perfectly fine locally and sends emails without any issues. However, once I push the project to Netlify, the email ...

Resize a div within another div using overflow scroll and centering techniques

Currently, I am working on implementing a small feature but am facing difficulties with the scroll functionality. My goal is to zoom in on a specific div by scaling it using CSS: transform: scale(X,Y) The issue I am encountering lies in determining the c ...

Unable to Retrieve Response from jQuery AJAX in a Function

Having some trouble with a jQuery AJAX function that is supposed to retrieve data from a file. I can't seem to get the function to return the actual value. Any suggestions? $(document).ready(function () { function fetchData() { ...

Struggling with the jquery .hover method

Encountering an issue with the jquery .hover function. It seems to only work if I place it inside a generic $(function(){. I have observed it being done without this generic function, so if anyone can point out what I might be doing incorrectly, I would be ...