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);
>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(", ")})`;