1

I have a dropdown-menu.

enter image description here


JS

$.each(responseData.assignments, function(i, v) {

    var assessmentId = v.assessmentId;
    var assessmentType = v.assessmentType;

    // Auto Populate the dropdown-menu
    $('#student-dd').append('<option value="' + assessmentId + '">' + assessmentType + '</option>');

});

Goal I want to show only one HOMEWORK/COURSE_BENCHMARK, doesn't matter how many of them are there. How can I check for uniqueness in Javascript ?

code-8
  • 54,650
  • 106
  • 352
  • 604

2 Answers2

3

You can check for length of option element with same text in that dropdown using filter function before appending new:

$.each(responseData.assignments, function(i, v) {

  var assessmentId = v.assessmentId;
  var assessmentType = v.assessmentType;

  // Auto Populate the dropdown-menu

  var optionwithsametext = $('#student-dd option').filter(function(){
      return $(this).text() == assessmentType ;
  })
  if(!optionwithsametext.length)
    $('#student-dd').append('<option value="' + assessmentId + '">' + assessmentType + '</option>');

 });
Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125
1

There is more than one way to do this. This is an another example;

var assignments = {};
$.each(responseData.assignments, function(i, v) {
    assignments[v.assessmentType] = v.assessmentId;
});

$.each(assignments, function(i, v) {
    // Auto Populate the dropdown-menu
    $('#student-dd').append('<option value="' + v + '">' + i + '</option>');
});
mocak
  • 405
  • 2
  • 5
  • 12