Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Not Able to Loop and Output Values From Two Separate Arrays Into One Single String

Can you please take a look at this code and let me know how I can loop into two arrays and create string output from both arrays statArr and typeArr with appending some AND & OR Operators

What I am hoping to get at the output is

stat = 'Closed' AND type = 'RD' OR
stat = 'Closed' AND type = 'WW' OR
stat = 'Closed' AND type = 'CC' OR
stat = 'Closed' AND type = 'MB' OR
stat = 'Closed' AND type = 'CN' OR
stat = 'Investigation' AND type = 'RD' OR
stat = 'Investigation' AND type = 'WW' OR
stat = 'Investigation' AND type = 'CC' OR
stat = 'Investigation' AND type = 'MB' OR
stat = 'Investigation' AND type = 'CN' 
var statArr = ["Closed", "Investigation"];
var typeArr = ["RD", "WW", "CC", "MB", "CN" ];
var sql = "";
for (let i = 0; i < statArr.length; i++) {
  sql += "stat = " + statArr[i] + " AND Type =";
 }
 console.log(sql);

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Nest two for loops to generate each stat/type combination, then join them with ORs. I added parentheses to each clause just to make sure precedence works as it should.

var statArr = ["Closed", "Investigation"];
var typeArr = ["RD", "WW", "CC", "MB", "CN" ];
var clauses = [];
for(var stat of statArr) {
  for(var type of typeArr) {
    clauses.push(`(stat = '${stat}' AND type = '${type}')`);
  }
}
var sql = clauses.join(" OR ");

The output is

(stat = 'Closed' AND type = 'RD') OR (stat = 'Closed' AND type = 'WW') OR (stat = 'Closed' AND type = 'CC') OR (stat = 'Closed' AND type = 'MB') OR (stat = 'Closed' AND type = 'CN') OR (stat = 'Investigation' AND type = 'RD') OR (stat = 'Investigation' AND type = 'WW') OR (stat = 'Investigation' AND type = 'CC') OR (stat = 'Investigation' AND type = 'MB') OR (stat = 'Investigation' AND type = 'CN')

However, I think you might really just want

stat IN ('Closed', 'Investigation') AND type IN ('RD', 'WW', 'CC', 'MB', 'CN')

which could be generated with

const quote = s => `'${s}'`;
var sql = `stat IN (${statArr.map(quote).join(", ")}) AND type IN (${typeArr.map(quote).join(", ")})`;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading