2

The following javascript code gives me the Don't make functions within a loop. error

/* Get the favorite products from the data using the id */
productDataCategory[FAVORITES].length = 0/* empty favorites productDataCategory */;
for ( i = 0; i < currentUser.favorites.length; i++) {
    product = $.grep(productData, function(e){ return e.id === currentUser.favorites[i]; })[0];
    productDataCategory[FAVORITES].push(p);
}

I've looked the question up and saw some similar questions asked by other members
How to get around the jslint error 'Don't make functions within a loop.'
Don't make functions within a loop

The problem I have is that I'm using a $.grep function inside the loop to find the product in an array.
I dont know how to resolve this issue with the answers in the above questions.


Data from a logged user

{
    "user": "MBO",
    "email": "my@mail.com",
    "username": "Marcel",
    "photoURL": "url_here",
    "favorites": [13,25,40,56]
}
Community
  • 1
  • 1
Marcel
  • 1,494
  • 1
  • 23
  • 33
  • 1
    Why don't use just a single `.grep` (instead of looping several of them), but check for `$.inArray(e.id, currentUser.favorites) !== -1` instead? Do you need the result array to be re-ordered by `currentUser.favorites` order? – raina77ow Oct 15 '12 at 09:18
  • Thats a really good question. Answer is that i never heard of $.inArray. That will make things quite faster! Using .grep for each product takes a lot of time! (I'll get into that) – Marcel Oct 15 '12 at 09:24
  • @raina77ow `.inArray` only gives locations. Does it handles multiple locations at once? (put in a whole array and get all the locations). If it doesn't, than it means I need to `.inArray` every product + get the data with the given location. `.grep` seems to be a better solution for that! – Marcel Oct 15 '12 at 09:36

1 Answers1

2

Put the function outside the loop:

/* Get the favorite products from the data using the id */
productDataCategory[FAVORITES].length = 0/* empty favorites productDataCategory */;
var f = function(e){ return e.id === currentUser.favorites[i]; };
for ( i = 0; i < currentUser.favorites.length; i++) {
  product = $.grep(productData, f)[0];
  productDataCategory[FAVORITES].push(p);
}
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • Worked like a charm. (btw i saw that you edited your answer! both are working, and the current is very neat) – Marcel Oct 15 '12 at 09:15