I have an array like this
const input_array= [ ["black", "blue"], ["large", "medium"], ["a", "b", "c"] //... is it dynamic can be added many rows ];
How would I get an array like this :
const finallist = [ ["black", "large", "a"], ["black", "large", "b"], ["black", "large", "c"], ["black", "medium", "a"], ["black", "medium", "b"], ["black", "medium", "c"], ["blue", "large", "a"], ["blue", "large", "b"], ["blue", "large", "c"], ["blue", "medium", "a"], ["blue", "medium", "b"], ["blue", "medium", "c"], ]
Please Remember input_array is dynamic
Please advice me how can I do this
Advertisement
Answer
Look at this, might be helpful:
const input_array = [ ["black", "blue"], ["large", "medium"], ["a", "b", "c"] //... is it dynamic can be added many rows ]; const mmc = input_array.reduce((e, r) => e * r.length, 1); const finallist = input_array.map((x,i)=>({index:i,arr:x})).reduce((e, r) => { for (var u = 0; u < mmc; u++) e[u] && (!r.arr.some(r => e[u].includes(r)) || e[u].length <= r.index) ? e[u].push(r.arr[u % r.arr.length]) : e.push([r.arr[u % r.arr.length]]); return e.sort(), e }, []);
Careful! This might break your browser in large matrix scales.