Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

208
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda