Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

207
Views
How to do math operation with an array from mongodb?

I have an array in mongodb, which contains objects with type of strings. These objects are only numbers but they are saved in mongodb as strings. I want to multiply each elements in the array, but i'm stucked, because when I convert the array elements from string to number, but not multiplying correctly. Here is my code for the array called quantity, which is converted from string to numbers:

<div>
      <p>Serving: <input type="number" name="serving" class="serving" step="any" value="2" min="1"></p>
      <input type="hidden" id="previousServing" value="5"/>
</div>

<div>
  <li class="ingredient">
    <% recipe.quantity.forEach(function(quantity, index){
      numarray = parseInt(quantity.toString())
      %>
      <span class="amount" id="amount"><%= numarray %></span>
    <% }) %>
  </li>
</div>

Here is my javascript code, where I want to do the math operation with each elements of the array (multiply with any number, what the user adding in textbox):

<script>
  $(function() {
    $('.serving').bind('keyup', function(event) {
      var previousValue = parseInt($("#previousServing").val());
      var newValue = parseInt($(event.target).val());
      if (previousValue && newValue) {
          $('.ingredient').each(function(index, elem) {
              var ingredientNow = $('.amount', elem);
              var oldIngredientAmount = ingredientNow.text();
              var newIngredientAmount = oldIngredientAmount * newValue / previousValue;
              ingredientNow.text(newIngredientAmount);
          });
          $('#previousServing').val(newValue);
      }
  });
});
</script>

Where should be the problem? I tested the converted array with typeoff and every element was number, and the output are random numbers, because when I done the math with the string array, I got an output numbers, but these was incorrect, and doing the same with the converted array.

UPDATE: Here is the array for example in mongodb

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!