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.
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});
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With