Skip to content Skip to sidebar Skip to footer

Javascript - Generating Combinations From Dictionary Keys And Keeping Key Names Dynamically

I found this excellent code which generates all the combinations of multiple arrays here: JavaScript - Generating combinations from n arrays with m elements I am now looking to go

Solution 1:

You can convert the array of objects into multi dimensional array. Construct possible combinations and use map to construct the final format.

var arr = [{"Footprint_Shape": ["L-Shape", "H-Shape", "T-Shape"]}, {"Num_of_Floors": [1, 2]}];

var result = arr.map(o =>Object.values(o)[0])                               //Convert the array of objects into multi dimensional array.
  .reduce((c, v) => [].concat(...c.map(o => v.map(x => [].concat(o, x)))))   //Make all possible combinations
  .map(([a, b]) => ({"Footprint_Shape": a,"Num_of_Floors": b}))              //Construct the final formatconsole.log(result);

Update:

var arr = [{"Footprint_Shape": ["L-Shape", "H-Shape", "T-Shape"]}, {"Num_of_Floors": [1, 2]}];

var keys = arr.map(o =>Object.keys(o)[0]); //Get the list of keysvar result = arr.map(o =>Object.values(o)[0]) //Convert the array of objects into multi dimensional array.
  .reduce((c, v) => [].concat(...c.map(o => v.map(x => [].concat(o, x))))) //Make all possible combinations
  .map(o => o.reduce((c, v, i) =>Object.assign(c, {[keys[i]]: v}), {})); //Construct the final formatconsole.log(result);

Solution 2:

A simple and short alternative:

const [{Footprint_Shape: shapes},{Num_of_Floors: floors} ] = [{"Footprint_Shape":["L-Shape","H-Shape","T-Shape"]},{"Num_of_Floors":[1,2]}];

const result = floors.reduce((all, floor) => {

    shapes.forEach(shape => all.push({Footprint_Shape: shape, Num_of_Floors: floor}))

    return all;

}, []);

console.log(result);

Solution 3:

let arr = [
  {"Footprint_Shape":["L-Shape","H-Shape","T-Shape"]},
  {"Num_of_Floors":[1,2]}
]

let answer = [];

arr[0]["Footprint_Shape"].forEach(x => {  
  
  arr[1]["Num_of_Floors"].forEach(y => {
    
    let newObj = {};  
    newObj["Footprint_Shape"] = x;
    //console.log('y: ',y)
    newObj["Num_of_Floors"] = y
  	answer.push(newObj);
    
  })
});

console.log(answer)

I think the code should be self explanatory. Using two looping, construct the object and push to a new array

Post a Comment for "Javascript - Generating Combinations From Dictionary Keys And Keeping Key Names Dynamically"