-1

I'm having trouble with JS loops. In fact i'm new to JS and I would like my script to iterate through 2 params which can take 2 values and then iterate another time through test values.

I came out with some code but it is pretty ugly and not optimized at all. I would like to know how to improve this code in a way that I can be able tu use variables easly in the inner loop.

Thanks a lot for your help !

const param_value_array = ['param1', 'param2']
const values = [true, false]
const test_value_array = ['0', '1', '0toto', '1toto']

values.forEach(param1_status => {
 values.forEach(param2_status => {
  test_value_array.forEach(test_value => {
      console.log('param1' + ' ' + param1_status + ' & '+ 'param2' + ' ' + param2_status + ' > ' + test_value)
  })
 })
}) 
sable
  • 1
  • 1
  • 1
    If you want to be able to add additional items to any of the 3 arrays in possible future refactoring, your current code looks fine enough to me. If `values` will only be `true` and `false`, iterating over it as an array might seem a *bit* weird, but it's not that bad IMO – CertainPerformance Nov 15 '19 at 09:37
  • 1
    you are looking for a [cartesian product](https://en.wikipedia.org/wiki/Cartesian_product). you may have some inspirations from here: https://stackoverflow.com/questions/12303989/cartesian-product-of-multiple-arrays-in-javascript. – Nina Scholz Nov 15 '19 at 09:39
  • 4
    This question is more suitable here: https://codereview.stackexchange.com/ – Sebastian Kaczmarek Nov 15 '19 at 09:49

1 Answers1

0

You haae nearly a clean solution:

const params = ['param1', 'param2']
const values = [true, false]
const tests = ['0', '1', '0toto', '1toto']

params
  .forEach(param => values
    .forEach(value => tests
      .forEach(test => doSomething(param,value,test))));
      
function doSomething(param,value,test){
  //Whatever
  console.log(param,value,test);
}
  
Serlox
  • 47
  • 3