Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

209
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda