-3

How can I replace the for loop with .each function?

    function addOptionsToSelect(placeElement, placeData){
      placeData.sort(comparePlaces);
      placeElement.empty();
      for(var i = 0; i < placeData.length; i++ ){
          var place = placeData[i];
          var option = $("<option>"+ place.name +"</option>").attr("value", place.code)
          placeElement.append(option);
      }
  }

4 Answers4

1

You could use Array#forEach, a native ES5 method, for it.

The forEach() method executes a provided function once per array element.

function addOptionsToSelect(placeElement, placeData){
    placeData.sort(comparePlaces);
    placeElement.empty();
    placeData.forEach(function (place) {
        var option = $("<option>"+ place.name +"</option>").attr("value", place.code);
        placeElement.append(option);
    });
}
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

DOM manipulation is costly.So create the entire set of options and add at once

 function addOptionsToSelect(placeElement, placeData){
      placeData.sort(comparePlaces);
      placeElement.empty();
     var option ="";
     placeData.forEach(function(item){
     option+ = $("<option>"+ item.name +"</option>").attr("value", item.code)
      })
     placeElement.append(option);
}
brk
  • 48,835
  • 10
  • 56
  • 78
0

A simple foreach syntax should do the job. The Javascript syntax uses a simple "for" inlcluding your objects keys:

function addOptionsToSelect(placeElement, placeData){
  placeData.sort(comparePlaces);
  placeElement.empty();

  for(var key in placeData)
  {
      place = placeData[key]
      var option = $("<option>"+ place.name +"</option>").attr("value", place.code)
      placeElement.append(option);
  }
}
hugodecasta
  • 262
  • 4
  • 13
  • In fact it's automatic, the "key" argument is deduced by the for statement so the key variable is generated from the object property. No check is required – hugodecasta Jun 07 '16 at 15:49
0

No one's actually posted it and people seem determined to answer this question, so for completeness, here's a version using jQuery.each:

function addOptionsToSelect(placeElement, placeData) {
    placeData.sort(comparePlaces);
    placeElement.empty();
    jQuery.each(placeData, function(_, place) { // Or $.each if $ == jQuery
        var option = $("<option>" + place.name + "</option>").attr("value", place.code)
        placeElement.append(option);
    });
}

Note that the first argument is the index of the entry; the entry itself is the second argument (and also this). Hence function(_, place) where we don't end up using the _ argument (_ is a valid identifier in JavaScript).

But I would use Array#forEach (shimmed if necessary) instead as Nina suggested or any of the many other ways to loop through arrays.

Community
  • 1
  • 1
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875