I want to sum all floats in an array
when I do this in the chrome console
$("tr.project_hours").find("td.number").map(function(i,v)
{return parseFloat($(v).attr("data-time"))
})
I get
[0, 0, 0, 0, 0, 0, 0]
This is what I want
But, in my code I have more $("tr.project_hours") and I want to sum them separately. So, I do
$("tr.project_hours").each(function(){
row = $(this).find('td.total')
row.html(sumInputsIn($(this).find("td.number").map(function(i,v){
return parseFloat($(v).attr("data-time"))})));
})
('td.total') is the column where the result should be displayed. The problem is that the last code returns this in the console
[0, 0, 0, 0, 0, 0, 0, prevObject: jQuery.fn.jQuery.init[7], context: <tr>]
So the result is the notorious NaN.
Why do I get the prevObject in my array? And how can I refactor to get rid of it?
The return type of calling map
on a jQuery collection is another jQuery collection. If you want to access just the results of the function used in the map, you need to use .toArray()
to return the underlying array instead:
var numbersArray = $("tr.project_hours").find("td.number").map(function(i,v)
{return parseFloat($(v).attr("data-time"))
}).toArray();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With