I have n number of arrays structured like
[{val_1: 2}, {val_1: 3}];
[{val_2: 2}];
[{val_3: 1}];
etc.
I want to create a single array structured like
[{val_1: 2, val_2: 2, val_3: 1}, {val_1: 3, val_2: 2, val_3: 1}]
in which all arrays are compared and every single possible output is produced. In the below code I have 3 arrays. One with 4 values, 2 values, and 3 values. I want it to return 24 different arrays showing all possible combinations.
var val_1 = 3
var val_2 = 2
var val_3 = 1
var total_val = 3;
var useable = 50;
var array_1 = new Array();
var array_2 = new Array();
var array_3 = new Array();
var array_1_c = new Array();
var array_2_c = new Array();
var array_3_c = new Array();
for(val_1; val_1 <= total_val && val_1 <= useable; val_1+=1){
array_1 = [{val_1}];
array_1.map(test =>{
return{val_1}
}).forEach(test => array_1_c.push(test));
};
var val_1 = 2
for(val_1; val_1 >= 0; val_1-=1){
array_1 = [{val_1}];
array_1.map(test =>{
return{val_1}
}).forEach(test => array_1_c.push(test));
};
for(val_2; val_2 <= total_val && val_2 <= useable; val_2+=1){
array_2 = [{val_2}];
array_2.map(test =>{
return{val_2}
}).forEach(test => array_2_c.push(test));
};
for(val_3; val_3 <= total_val && val_3 <= useable; val_3+=1){
array_3 = [{val_3}];
array_3.map(test =>{
return{val_3}
}).forEach(test => array_3_c.push(test));
}; console.log(array_1_c);console.log(array_2_c);console.log(array_3_c);
how would something like this be accomplished? The permute function seems to be the way to go, but I can't find a way to output every single combination. If creating multiple million combinations should I go a different route than using an object array.
Thanks!
You could take an algorithm for a cartesian product by using arrays of objects.
The result is an array of object with all properties of the given data.
const getCartesian = array => array.reduce((a, b) => a.reduce((r, v) => r.concat(b.map(w => ({...v, ...w }))), [])), all = [[{ val_1: 2 }, { val_1: 3 }], [{ val_2: 2 }], [{ val_3: 1 }]], cartesian = getCartesian(all); console.log(cartesian);
.as-console-wrapper { max-height: 100%;important: top; 0; }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.