Search code examples
javascriptarraysgoogle-apps-scriptgoogle-sheetsnsarray

Having some problem in my calculation with javscript


I am trying to add a the values in an array untill the sum is 1000. I have been trying it using for loop with if condition. but it doesn't stop in according with sum value. example array [110.110.225,130,150,100,240,170,100,110,...] I want the loop to be stopped once the sum of values = 1000 or any other specific sum. Need help please.


Solution

  • function stopWhenSumEqualsN(n,A) {
      var n=n||500;
      var A=A||[110,110,225,130,150,100,240,170,100,110];
      let obj=A.reduce(function(a,v,i){
        if(a.sum<a.threshold) {
          a.sum+=Number(v);
          a.maxidx+=Number(1);
        }
        return a;
      },{sum:0,maxidx:0,threshold:n});
      let msg=Utilities.formatString('sum: %s maxidx: %s threshold: %s',obj.sum,obj.maxidx,obj.threshold);
      msg+='<br /><input type="text" id="nin" value="' + n + '" /> n<br />';
      msg+='<textarea id="Ain" rows="4" cols="60">' + A.join(",") +  '</textarea>A<br /><input type="button" value="Execute" onclick="runAgain();" />';
      msg+='<input type="button" value="Start Again From Scratch" onClick="google.script.run.stopWhenSumEqualsN();" />';
      msg+='<script>function runAgain(){let n=document.getElementById("nin").value;let A=document.getElementById("Ain").value.split(",");google.script.run.stopWhenSumEqualsN(n,A);}</script>'; 
      SpreadsheetApp.getUi().showModelessDialog(HtmlService.createHtmlOutput(msg), "Results");
    }