Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery is adding prevObject: to array

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?

like image 593
Andreas Lyngstad Avatar asked Jan 07 '13 09:01

Andreas Lyngstad


1 Answers

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();
like image 196
steveukx Avatar answered Sep 26 '22 03:09

steveukx