Matrix array algorithm logic in javascript Matrix array algorithm logic in javascript

Need some help in solving this algorithm in javascript. How to write solution considering time complexity. Considering the maximum key value is 3.

input1 = [{0: "small"},{0: "large"}]
output1 = [ 'small.', 'large.']
-----------------------------------------
input2 = [ {0: "small"},{0: "large"}, {1: "red"} ]
output2 = ['small.red', 'large.red']
-----------------------------------------
input3 = [{0: "small"},{0: "large"}, {1: "red"}, {2:"cake"} ]
output3 = ['small.red.cake', 'large.red.cake'}
-----------------------------------------
input4 = [{0: "small"},{0: "large"}, {1: "red"}, {1: "orange"}, {2: "cake"} ]
output4 = ['small.red.cake', 'large.red.cake', 'small.orange.cake', 'large.orange.cake'}
------------------------------------------
input5 = [ {0: "small"},{0: "large"}, {1: "red"},{1: "orange"},{1: "blue"},{2: "cake"},{2: "ice"}]
output5 = ['small.red.cake', 'large.red.cake', 'small.orange.cake', 'large.orange.cake', 'small.blue.cake', 'large.blue.cake', 'small.red.ice', 'large.red.ice', 'small.orange.ice', 'large.orange.ice', 'small.blue.ice', 'large.blue.ice']
] //12 combinations

My attempt i purposely checking the index in if condition. and it is working as expected. Looking for the best solution.

const input5 = [ {0: "small"},{0: "large"}, {1: "red"},{1: "orange"},{1: "blue"},{2: "cake"},{2: "ice"}]

 let array1 = [];
let array2 = [];
let array3 = [];
input5.forEach(val => {
  if(val[0]) {
    array1.push(val[0]);
  }
  if(val[1]) {
    array2.push(val[1]);
  }
  if(val[2]) {
    array3.push(val[2]);
  }
});
const finalArray = [];
array1.forEach(val1 => {
  if(array2.length > 0) {
     array2.forEach(val2 => {
       if(array3.length > 0) {
         array3.forEach(val3 => {
           const finalVal = `${val1}.${val2}.${val3}`;
           finalArray.push(finalVal);
         })
       }else {
         const finalVal = `${val1}.${val2}`;
         finalArray.push(finalVal);
       }
     })
  }else {
    const finalVal = `${val1}.`;
    finalArray.push(finalVal);
  }
})
console.log(finalArray);


from Stackoverflow

Comments

Popular posts from this blog

How can I get every LI element's innerHTML and display as string? How can I get every LI element's innerHTML and display as string?

Refresh page after clicking button (ok / cancel) Refresh page after clicking button (ok / cancel)

I am having trouble with this ajax timer it is not doing what I expect and does not execute I am having trouble with this ajax timer it is not doing what I expect and does not execute