1

I need to sum all the prices inside an array so i can now the full price of all orders (the full price of all the items inside this array) in my application. But when i try to do it using the method .map i get "0" as the value. Im adding to my array all the values from the inputs that have the class ".total", not sure if this can be the issue

Can anybody help me?

enter image description here

var inputs = $(".total");
var arrTotal = [];

for (var i = 0; i < inputs.length; i++) {
    arrTotal.push($(inputs[i]).val().replace("R$", ""));
}

let sum = 0;
arrTotal.map(e => sum += e)
console.log(sum);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script>
<input class='total' value="1">
<input class='total' value="2">
<input class='total' value="3">
freedomn-m
  • 27,664
  • 8
  • 35
  • 57
  • 2
    Does this answer your question? [Better way to sum a property value in an array](https://stackoverflow.com/questions/23247859/better-way-to-sum-a-property-value-in-an-array) – Heretic Monkey Mar 24 '23 at 13:36
  • 2
    Don't use `.map()` like a for-each, if you're not building a new array, use a `.forEach()` (And, since you are already looping through everything, do the summing inside your first loop instead of looping through twice) – DBS Mar 24 '23 at 13:37
  • 1
    You'll get "0" if you don't have an inputs with class `.total`. I've taken the liberty of adding some inputs to your snippet to match the screenshot - but now you you'll see the result is the "numbers" concatenated together - because your arrTotal is an array of *strings* (as also shown in the image). And `"1" + "2" = "12"`. Add your values to arrTotal as numeric values. easiest: `arrTotal.push($(inputs[i]).val().replace("R$", "") * 1);` – freedomn-m Mar 24 '23 at 13:48
  • 2
    Or use `reduce`, as indicated in the dupe, @DBS :). – Heretic Monkey Mar 24 '23 at 13:48
  • @freedomn-m all the items are being returned as NaN – Paulo Paiva Mar 24 '23 at 13:50
  • Then pick another method to convert text to a number (maybe [search on SO](https://stackoverflow.com/questions/2843897/javascript-converting-string-to-number)?). Looks like you're using a non-US-centric locale (ie "0,00"). – freedomn-m Mar 24 '23 at 13:56

1 Answers1

2
var inputs = $(".total");
var arrTotal = [];

for (var i = 0; i < inputs.length; i++) {
    arrTotal.push(Number($(inputs[i]).val()));
}

let sum = arrTotal.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
console.log(sum);

Use the reduce() function to sum up all the values in the arrTotal array. Since the val() method returns the value of an input element as a string. And don't know whether the value will be an integer or a floating-point number, I used Number()

Ayb009
  • 220
  • 2
  • 11