0

Trying to populate a drowpdown box based on a json object. So data holds items returned from a table, where item_number. The below function works, but if there are duplicate item_number entries, so the options end up like this: 1,2,3,3,3. How do I group the 3 item_numbers ?

//populate #number dropdown
function numbers(data,n) {
    $("#number option:not(:first)").remove();
    var options = $("#number");
    $.each(data, function() {
        if(this.item_number != 0)
        {
            options.append($("<option />").val(this.item_number).text(this.item_number));
        }
    });

    var dropVal = (n != "" ? n : "Issue nr.");
    $("#number").val( dropVal );
}

And for bonus points ... how do I order them in ASC order? At the moment, they are mixed up. Can jquery order them?

Ciprian
  • 3,066
  • 9
  • 62
  • 98
  • You want to remove or group? I am not getting what do you mean by group – Imad Jun 18 '15 at 07:59
  • And please show me server code – Imad Jun 18 '15 at 07:59
  • I just don't want to have duplicate numbers in the dropdown. So if I return 5 items from the database. And let's say their item_numbers are 1, 2, 3, 4, 4 ... I want to have 1, 2, 3, 4 in the dropdown, not 1, 2, 3, 4, 4 – Ciprian Jun 18 '15 at 08:00
  • How you are collection that data? please share code – Imad Jun 18 '15 at 08:02

2 Answers2

0

You can first create an array with non-repeating values and use that array to build options. Or can be in use in other places as well once you filter and create an array of non-repeating values

var myArray = new Array();
$.each(data, function() {
    if(this.item_number != 0){
       if( $.inArray(this.item_number, myArray) == -1 ){
         myArray.push(this.item_number);
      }
 }
Suman KC
  • 3,478
  • 4
  • 30
  • 42
0

You can create an object with item_number as key and value. This will remove duplicate. Now create an array out of this object and sort it.

Vikash
  • 1,109
  • 1
  • 12
  • 19