Question,

I have a $each(array, function()); and within that statement, i have afor loop , Is it safe to be doing this? and could this be the reason that i am getting the same values multiple times returned even though the object array length is 8, i am getting basically doubled up results, sometimes its more. if you need to see my code, i can post it.

Your for loop will be executed once per iteration of your $.each loop.

If that's what you intend to do, then it's not dangerous. Perhaps posting an example of your code (use jsfiddle or similar) would help you explain exacctly what your concerns are.

Additionally, the two types of loop can be used for the same purpose, they are just different syntax (there are other differences but let's not complicate things).

Hi PTY, here is my Fiddle its just showing the js code i am using.

Fiddle

here is the output

another screenshot

A few points.

You are looping through dutyStatusLogs multiple times in different ways. You're calling dutyStatusLogs.forEach twice and $.each(dutyStatusLogs, function(i,v){...}) once. These should probably be combined into one loop.

Now, what your original question was about, the nested loop

        $.each(dutyStatusLogs, function(index, value) {

                    var json = dutyStatusLogs;

                        var tr;
               for (var i = 0; i < json.length; i++) {
               }

This section doesn't look right to me. You don't appear to be using the outer loop for anything (there are no references to index or value inside the $.each loop), and you're executing the inner loop once per iteration.

I would rewrite that section in the following manner:

$.each(dutyStatusLogs, function(index, dsl) {
    var dateFieldValue = dsl.dateTime;
    var employeeNo = dsl.driver.employeeNo ;
    var status = dsl.status;

    ...
});

Note I'm using variable dsl (for dutyStatusLog) instead of accessing the original array with the index, this is one of the benefts of using jQuery's $.each function. Newer JavaScript allows for an even simpler syntax. If that's an option you can make your code more readable by using it.

for (variable of iterable) {
  statement
};

What the problem if you are using a for loop inside the jQuery each method.

Your code may be something like this:

$(".someclass").each(function (index, value) { 
  //for loop doing some calculation. 
}); 

It is perfectly ok.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.