Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript generate matrix from two object arrays

Trying to convert an infinite number of object arrays into a matrix.

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

into

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

Basically map out all possible combination into a matrix

I tried solving the problem using a few 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 slightly more complicated in my case since I have to split the string values entered into array. But to ease coming up with solution I omitted that the values are comma separated strings

This is not a duplicate of other similar questions, cause am trying obtain all permutations of an object like on below

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

the existing solutions only find permutations for arrays, not an object. the values of each key will always be comma separated, so object[ key ].split(",") will return values as array.

If it were possible to concatenate arguments to call function I could make use of one of the existing functions.

like image 581
isawk Avatar asked Sep 17 '25 09:09

isawk


1 Answers

Sure thing, you could use a double for:

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]});

The array called result at the end will contain all the possible combinations of height and weight.

Another way it would be you use the forEach method of array:

var result = [];
height.forEach(function(h){
    weight.forEach(function(w){
         result.push({ height: h, weight: w});    
    });
});
like image 155
Christos Avatar answered Sep 19 '25 03:09

Christos