Browse a numeric data array and add or subtract during the loop with $.each












1














It may be that this question has already been posted, but I have not found any clear solution to my problem.



The title of my question has already described my problem. In fact I wish to see the sum of the sum during the loop. But when you meet a negative number, it turns into a positive number. Which distorts the result.
Below an example of my loop.



Can you help me please ?



<table>
<tr id="testTable">
<td data-pos="0"></td>
<td data-pos="1"></td>
<td data-pos="2"></td>
<td data-pos="3"></td>
<td data-pos="4"></td>
<td data-pos="5"></td>
</tr>
</table>

<script>
$(document).ready(function () {
var array = [200, 400, 200, -500, 200,100];

var sum = 0;
$.each(array, function (i, val) {
val = parseFloat(val);
if ($.isNumeric(val)) {
if (val > 0) {
sum += val;
} else {
sum -= val;
}
}
$('tr#testTable td[data-pos="'+i+'"]').text(sum);
});
});
</script>


The result is 1600 instead of 600



Thanks a lot for your help










share|improve this question






















  • Do you really need to use $.each()? Why not Array.reduce?
    – Praveen Kumar Purushothaman
    yesterday










  • Why you do not want to use reduce?
    – Just code
    yesterday
















1














It may be that this question has already been posted, but I have not found any clear solution to my problem.



The title of my question has already described my problem. In fact I wish to see the sum of the sum during the loop. But when you meet a negative number, it turns into a positive number. Which distorts the result.
Below an example of my loop.



Can you help me please ?



<table>
<tr id="testTable">
<td data-pos="0"></td>
<td data-pos="1"></td>
<td data-pos="2"></td>
<td data-pos="3"></td>
<td data-pos="4"></td>
<td data-pos="5"></td>
</tr>
</table>

<script>
$(document).ready(function () {
var array = [200, 400, 200, -500, 200,100];

var sum = 0;
$.each(array, function (i, val) {
val = parseFloat(val);
if ($.isNumeric(val)) {
if (val > 0) {
sum += val;
} else {
sum -= val;
}
}
$('tr#testTable td[data-pos="'+i+'"]').text(sum);
});
});
</script>


The result is 1600 instead of 600



Thanks a lot for your help










share|improve this question






















  • Do you really need to use $.each()? Why not Array.reduce?
    – Praveen Kumar Purushothaman
    yesterday










  • Why you do not want to use reduce?
    – Just code
    yesterday














1












1








1







It may be that this question has already been posted, but I have not found any clear solution to my problem.



The title of my question has already described my problem. In fact I wish to see the sum of the sum during the loop. But when you meet a negative number, it turns into a positive number. Which distorts the result.
Below an example of my loop.



Can you help me please ?



<table>
<tr id="testTable">
<td data-pos="0"></td>
<td data-pos="1"></td>
<td data-pos="2"></td>
<td data-pos="3"></td>
<td data-pos="4"></td>
<td data-pos="5"></td>
</tr>
</table>

<script>
$(document).ready(function () {
var array = [200, 400, 200, -500, 200,100];

var sum = 0;
$.each(array, function (i, val) {
val = parseFloat(val);
if ($.isNumeric(val)) {
if (val > 0) {
sum += val;
} else {
sum -= val;
}
}
$('tr#testTable td[data-pos="'+i+'"]').text(sum);
});
});
</script>


The result is 1600 instead of 600



Thanks a lot for your help










share|improve this question













It may be that this question has already been posted, but I have not found any clear solution to my problem.



The title of my question has already described my problem. In fact I wish to see the sum of the sum during the loop. But when you meet a negative number, it turns into a positive number. Which distorts the result.
Below an example of my loop.



Can you help me please ?



<table>
<tr id="testTable">
<td data-pos="0"></td>
<td data-pos="1"></td>
<td data-pos="2"></td>
<td data-pos="3"></td>
<td data-pos="4"></td>
<td data-pos="5"></td>
</tr>
</table>

<script>
$(document).ready(function () {
var array = [200, 400, 200, -500, 200,100];

var sum = 0;
$.each(array, function (i, val) {
val = parseFloat(val);
if ($.isNumeric(val)) {
if (val > 0) {
sum += val;
} else {
sum -= val;
}
}
$('tr#testTable td[data-pos="'+i+'"]').text(sum);
});
});
</script>


The result is 1600 instead of 600



Thanks a lot for your help







jquery






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked yesterday









Yona Smilevitch

518




518












  • Do you really need to use $.each()? Why not Array.reduce?
    – Praveen Kumar Purushothaman
    yesterday










  • Why you do not want to use reduce?
    – Just code
    yesterday


















  • Do you really need to use $.each()? Why not Array.reduce?
    – Praveen Kumar Purushothaman
    yesterday










  • Why you do not want to use reduce?
    – Just code
    yesterday
















Do you really need to use $.each()? Why not Array.reduce?
– Praveen Kumar Purushothaman
yesterday




Do you really need to use $.each()? Why not Array.reduce?
– Praveen Kumar Purushothaman
yesterday












Why you do not want to use reduce?
– Just code
yesterday




Why you do not want to use reduce?
– Just code
yesterday












2 Answers
2






active

oldest

votes


















3














You can actually use .reduce(). Coming to your question, the problem is in the if condition. Let's say the value is -500.



if (val > 0) {
sum += val;
} else {
// val is -500 and it comes here.
// sum will be set to sum - (-500)
// the above will be sum + 500
sum -= val;
}


Your logic here is flawed.



You just need to use:



if ($.isNumeric(val)) {
sum += val;
}


Snippet






<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr id="testTable">
<td data-pos="0"></td>
<td data-pos="1"></td>
<td data-pos="2"></td>
<td data-pos="3"></td>
<td data-pos="4"></td>
<td data-pos="5"></td>
</tr>
</table>

<script>
$(document).ready(function() {
var array = [200, 400, 200, -500, 200, 100];

var sum = 0;
$.each(array, function(i, val) {
val = parseFloat(val);
if ($.isNumeric(val)) {
sum += val;
}
$('tr#testTable td[data-pos="' + i + '"]').text(sum);
});
});
</script>





I am indeed getting 600 as the answer above.






share|improve this answer





























    0














    Your problem sources from the if condition that you are using. You don't need to check whether the value is negative or positive, but just to add it in the sum.
    When you check if the value is negative, in reality it reverses the sign of the number, which means that a negative number becomes positive.

    I would recommend the use of .reduce, rather the unnecessary declaration of variables. However, the solution with $.each would be:



    $.each(callback)



    let array = [200, 400, 200, -500, 200, 100];
    let s = 0;
    $.each(array, (i,v)=> s + v);


    A simpler solution with vanillaJS is:



    let sum = [200, 400, 200, -500, 200,100].reduce((s,v) => s + v ,0)





    share|improve this answer























    • The question specifically says they want to use $.each()
      – Praveen Kumar Purushothaman
      yesterday










    • Yeap. I didn't read correctly that question.
      – Marios Simou
      yesterday











    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53944394%2fbrowse-a-numeric-data-array-and-add-or-subtract-during-the-loop-with-each%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    3














    You can actually use .reduce(). Coming to your question, the problem is in the if condition. Let's say the value is -500.



    if (val > 0) {
    sum += val;
    } else {
    // val is -500 and it comes here.
    // sum will be set to sum - (-500)
    // the above will be sum + 500
    sum -= val;
    }


    Your logic here is flawed.



    You just need to use:



    if ($.isNumeric(val)) {
    sum += val;
    }


    Snippet






    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <table>
    <tr id="testTable">
    <td data-pos="0"></td>
    <td data-pos="1"></td>
    <td data-pos="2"></td>
    <td data-pos="3"></td>
    <td data-pos="4"></td>
    <td data-pos="5"></td>
    </tr>
    </table>

    <script>
    $(document).ready(function() {
    var array = [200, 400, 200, -500, 200, 100];

    var sum = 0;
    $.each(array, function(i, val) {
    val = parseFloat(val);
    if ($.isNumeric(val)) {
    sum += val;
    }
    $('tr#testTable td[data-pos="' + i + '"]').text(sum);
    });
    });
    </script>





    I am indeed getting 600 as the answer above.






    share|improve this answer


























      3














      You can actually use .reduce(). Coming to your question, the problem is in the if condition. Let's say the value is -500.



      if (val > 0) {
      sum += val;
      } else {
      // val is -500 and it comes here.
      // sum will be set to sum - (-500)
      // the above will be sum + 500
      sum -= val;
      }


      Your logic here is flawed.



      You just need to use:



      if ($.isNumeric(val)) {
      sum += val;
      }


      Snippet






      <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
      <table>
      <tr id="testTable">
      <td data-pos="0"></td>
      <td data-pos="1"></td>
      <td data-pos="2"></td>
      <td data-pos="3"></td>
      <td data-pos="4"></td>
      <td data-pos="5"></td>
      </tr>
      </table>

      <script>
      $(document).ready(function() {
      var array = [200, 400, 200, -500, 200, 100];

      var sum = 0;
      $.each(array, function(i, val) {
      val = parseFloat(val);
      if ($.isNumeric(val)) {
      sum += val;
      }
      $('tr#testTable td[data-pos="' + i + '"]').text(sum);
      });
      });
      </script>





      I am indeed getting 600 as the answer above.






      share|improve this answer
























        3












        3








        3






        You can actually use .reduce(). Coming to your question, the problem is in the if condition. Let's say the value is -500.



        if (val > 0) {
        sum += val;
        } else {
        // val is -500 and it comes here.
        // sum will be set to sum - (-500)
        // the above will be sum + 500
        sum -= val;
        }


        Your logic here is flawed.



        You just need to use:



        if ($.isNumeric(val)) {
        sum += val;
        }


        Snippet






        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
        <table>
        <tr id="testTable">
        <td data-pos="0"></td>
        <td data-pos="1"></td>
        <td data-pos="2"></td>
        <td data-pos="3"></td>
        <td data-pos="4"></td>
        <td data-pos="5"></td>
        </tr>
        </table>

        <script>
        $(document).ready(function() {
        var array = [200, 400, 200, -500, 200, 100];

        var sum = 0;
        $.each(array, function(i, val) {
        val = parseFloat(val);
        if ($.isNumeric(val)) {
        sum += val;
        }
        $('tr#testTable td[data-pos="' + i + '"]').text(sum);
        });
        });
        </script>





        I am indeed getting 600 as the answer above.






        share|improve this answer












        You can actually use .reduce(). Coming to your question, the problem is in the if condition. Let's say the value is -500.



        if (val > 0) {
        sum += val;
        } else {
        // val is -500 and it comes here.
        // sum will be set to sum - (-500)
        // the above will be sum + 500
        sum -= val;
        }


        Your logic here is flawed.



        You just need to use:



        if ($.isNumeric(val)) {
        sum += val;
        }


        Snippet






        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
        <table>
        <tr id="testTable">
        <td data-pos="0"></td>
        <td data-pos="1"></td>
        <td data-pos="2"></td>
        <td data-pos="3"></td>
        <td data-pos="4"></td>
        <td data-pos="5"></td>
        </tr>
        </table>

        <script>
        $(document).ready(function() {
        var array = [200, 400, 200, -500, 200, 100];

        var sum = 0;
        $.each(array, function(i, val) {
        val = parseFloat(val);
        if ($.isNumeric(val)) {
        sum += val;
        }
        $('tr#testTable td[data-pos="' + i + '"]').text(sum);
        });
        });
        </script>





        I am indeed getting 600 as the answer above.






        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
        <table>
        <tr id="testTable">
        <td data-pos="0"></td>
        <td data-pos="1"></td>
        <td data-pos="2"></td>
        <td data-pos="3"></td>
        <td data-pos="4"></td>
        <td data-pos="5"></td>
        </tr>
        </table>

        <script>
        $(document).ready(function() {
        var array = [200, 400, 200, -500, 200, 100];

        var sum = 0;
        $.each(array, function(i, val) {
        val = parseFloat(val);
        if ($.isNumeric(val)) {
        sum += val;
        }
        $('tr#testTable td[data-pos="' + i + '"]').text(sum);
        });
        });
        </script>





        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
        <table>
        <tr id="testTable">
        <td data-pos="0"></td>
        <td data-pos="1"></td>
        <td data-pos="2"></td>
        <td data-pos="3"></td>
        <td data-pos="4"></td>
        <td data-pos="5"></td>
        </tr>
        </table>

        <script>
        $(document).ready(function() {
        var array = [200, 400, 200, -500, 200, 100];

        var sum = 0;
        $.each(array, function(i, val) {
        val = parseFloat(val);
        if ($.isNumeric(val)) {
        sum += val;
        }
        $('tr#testTable td[data-pos="' + i + '"]').text(sum);
        });
        });
        </script>






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered yesterday









        Praveen Kumar Purushothaman

        131k23135181




        131k23135181

























            0














            Your problem sources from the if condition that you are using. You don't need to check whether the value is negative or positive, but just to add it in the sum.
            When you check if the value is negative, in reality it reverses the sign of the number, which means that a negative number becomes positive.

            I would recommend the use of .reduce, rather the unnecessary declaration of variables. However, the solution with $.each would be:



            $.each(callback)



            let array = [200, 400, 200, -500, 200, 100];
            let s = 0;
            $.each(array, (i,v)=> s + v);


            A simpler solution with vanillaJS is:



            let sum = [200, 400, 200, -500, 200,100].reduce((s,v) => s + v ,0)





            share|improve this answer























            • The question specifically says they want to use $.each()
              – Praveen Kumar Purushothaman
              yesterday










            • Yeap. I didn't read correctly that question.
              – Marios Simou
              yesterday
















            0














            Your problem sources from the if condition that you are using. You don't need to check whether the value is negative or positive, but just to add it in the sum.
            When you check if the value is negative, in reality it reverses the sign of the number, which means that a negative number becomes positive.

            I would recommend the use of .reduce, rather the unnecessary declaration of variables. However, the solution with $.each would be:



            $.each(callback)



            let array = [200, 400, 200, -500, 200, 100];
            let s = 0;
            $.each(array, (i,v)=> s + v);


            A simpler solution with vanillaJS is:



            let sum = [200, 400, 200, -500, 200,100].reduce((s,v) => s + v ,0)





            share|improve this answer























            • The question specifically says they want to use $.each()
              – Praveen Kumar Purushothaman
              yesterday










            • Yeap. I didn't read correctly that question.
              – Marios Simou
              yesterday














            0












            0








            0






            Your problem sources from the if condition that you are using. You don't need to check whether the value is negative or positive, but just to add it in the sum.
            When you check if the value is negative, in reality it reverses the sign of the number, which means that a negative number becomes positive.

            I would recommend the use of .reduce, rather the unnecessary declaration of variables. However, the solution with $.each would be:



            $.each(callback)



            let array = [200, 400, 200, -500, 200, 100];
            let s = 0;
            $.each(array, (i,v)=> s + v);


            A simpler solution with vanillaJS is:



            let sum = [200, 400, 200, -500, 200,100].reduce((s,v) => s + v ,0)





            share|improve this answer














            Your problem sources from the if condition that you are using. You don't need to check whether the value is negative or positive, but just to add it in the sum.
            When you check if the value is negative, in reality it reverses the sign of the number, which means that a negative number becomes positive.

            I would recommend the use of .reduce, rather the unnecessary declaration of variables. However, the solution with $.each would be:



            $.each(callback)



            let array = [200, 400, 200, -500, 200, 100];
            let s = 0;
            $.each(array, (i,v)=> s + v);


            A simpler solution with vanillaJS is:



            let sum = [200, 400, 200, -500, 200,100].reduce((s,v) => s + v ,0)






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited yesterday

























            answered yesterday









            Marios Simou

            323




            323












            • The question specifically says they want to use $.each()
              – Praveen Kumar Purushothaman
              yesterday










            • Yeap. I didn't read correctly that question.
              – Marios Simou
              yesterday


















            • The question specifically says they want to use $.each()
              – Praveen Kumar Purushothaman
              yesterday










            • Yeap. I didn't read correctly that question.
              – Marios Simou
              yesterday
















            The question specifically says they want to use $.each()
            – Praveen Kumar Purushothaman
            yesterday




            The question specifically says they want to use $.each()
            – Praveen Kumar Purushothaman
            yesterday












            Yeap. I didn't read correctly that question.
            – Marios Simou
            yesterday




            Yeap. I didn't read correctly that question.
            – Marios Simou
            yesterday


















            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.





            Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


            Please pay close attention to the following guidance:


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53944394%2fbrowse-a-numeric-data-array-and-add-or-subtract-during-the-loop-with-each%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Monofisismo

            Angular Downloading a file using contenturl with Basic Authentication

            Olmecas