2

I've a small code snippet in react JS wherein I'm trying to search for a value in an object 'categories' and then inserting the corresponding key-value pair in a new map sortedCategories.

var categoriesToSort = []; //categoriesToSort has some values
var sortedCategories = new Map();
for(var j = 0 ; j < categoriesToSort.length ; j++) {
    categories.forEachMap(function(key, value){
       if(categoriesToSort[j] === value) {
          sortedCategories.set(key, value);
       }
    });
}

But this is giving me the following lint error and I'm not getting any workaround.

Don't make functions within a loop

Alexander O'Mara
  • 58,688
  • 18
  • 163
  • 171
aaggarwal
  • 61
  • 1
  • 4
  • This has been asked [once or twice before](http://stackoverflow.com/search?q=%5Bjslint%5D+Don%27t+make+functions+within+a+loop). Good answer [here](http://stackoverflow.com/a/3038555/1028230), among others. Voting to close. – ruffin Jun 01 '16 at 17:18

2 Answers2

0

How about using forEach instead of a for loop?

var categoriesToSort = []; //categoriesToSort has some values
var sortedCategories = new Map();
categoriesToSort.forEach(function (cat) {
    categories.forEachMap(function(key, value){
       if(cat === value) {
          sortedCategories.set(key, value);
       }
    });
});
elwyn
  • 10,360
  • 11
  • 42
  • 52
0

I don't see any reason refactoring your code like this won't work. Basically we take the callback function out of the loop, and use the j variable as it is in the closure. I've moved the var j declaration above the callback to make it look nice, but technically you don't have to.

var categoriesToSort = []; //categoriesToSort has some values
var sortedCategories = new Map();
var j;
var itter = function(key, value) {
    if(categoriesToSort[j] === value) {
        sortedCategories.set(key, value);
    }
};
for(j = 0 ; j < categoriesToSort.length ; j++) {
    categories.forEachMap(itter);
}
Alexander O'Mara
  • 58,688
  • 18
  • 163
  • 171
  • Hey thanks ! This works. But, what if I want to break out of the forEachMap once it has found the value and set in the map. How can we do that ? – aaggarwal May 31 '16 at 04:32
  • @aaggarwal You could just do: `j = categoriesToSort.length;` in the callback, or have another variable in the loop condition you set to false to break it. – Alexander O'Mara May 31 '16 at 04:36
  • To "break out" of `forEach`, use something like `some` instead. –  May 31 '16 at 05:24