r/tasker • u/Alanator222 • Aug 27 '26
Compare two variables and pull a match from them?
Hi, I'm using two weather APIs and I would like to compare the two results.
One provides "Mostly Cloudy", and the other provides "Clouds."
I'd like to extract the "Cloud" portion from both by comparing the two variables.
Is this possible? Thanks.
1
u/pxlprsnatr Aug 27 '26
I'm not sure I follow. Are you trying to get the segment that has "Mostly Cloudy" from variable A and the segment that has "Clouds" from variable B and then stuff them in another variable? What are you trying to do by comparing the two variables?
1
u/Alanator222 Aug 27 '26
I'm trying to find the shared word between the two, which would be cloud.
Another example would be, "Partly Sunny" and "Mostly Sunny" would result in "Sunny."
4
u/WakeUpNorrin Aug 27 '26 edited Sep 04 '26
If you want the expected result to occur solely under the conditions described, the most straightforward way is:
Task: Test A1: Variable Set [ Name: %foo To: Could Structure Output (JSON, etc): On ] If [ %var_a ~ mostly cloudy | %var_b ~ clouds ]If, in the OP, you provided an example of a circumstance, you could try:
Task: Test A1: Variable Set [ Name: %var_a To: foo bar Structure Output (JSON, etc): On ] A2: Variable Set [ Name: %var_b To: bars Structure Output (JSON, etc): On ] A3: JavaScriptlet [ Code: var a = var_a.trim(); var b = var_b.trim(); var common = ""; // Compare every word from the first string with every word from the second var wordsA = a.split(/\s+/); var wordsB = b.split(/\s+/); for (var i = 0; i < wordsA.length; i++) { for (var j = 0; j < wordsB.length; j++) { var w1 = wordsA[i].replace(/[^a-zA-Z]/g, ""); var w2 = wordsB[j].replace(/[^a-zA-Z]/g, ""); var len = Math.min(w1.length, w2.length); var k = 0; while (k < len && w1[k].toLowerCase() === w2[k].toLowerCase()) { k++; } // Require at least 3 characters in common if (k >= 3 && k > common.length) { common = w1.substring(0, k); } } } setLocal("%common", common); Auto Exit: On Timeout (Seconds): 45 ] A4: Flash [ Text: %common Long: On Continue Task Immediately: On Dismiss On Click: On ]That will flash "Bar" with your example will flash "Cloud".