1

I'm trying to populate my drop down in certain order (alphabetical order/alpha numeric order), but my code doesn't seems to be working. It is populating the value but not in order.

Here is my code

function dropdown(){
    var html = html + "<option value='All'>All</option>";
    var colValue = getColumn("COLUMN");
    for( var i = 0; i < colValue.length; i++ ) {
        var valueRow = colValue[i];
        html = html + "<option value='" + valueRow.c + "'>" + valueRow.c + "-" + valueRow.v + "</option>";
    }
    $('#id').append(html);    

}

here, COLUMN is the key that holds the value A1,A2,A3,B1

this code populate my drop down in the order A3,A1,A2,B1

I want my drop down to populate in the order A1,A2,A3,B1

while i did alert(html);i get the result

<option value='All'>All   </option>";
<option value='A3'>A3-a3Value </option>";
<option value='A2'>A1-a2Value </option>";
<option value='A1'>A2-a1Value </option>";
<option value='B1'>B1-b1Value </option>";

and it is populating exactly in the same order.

My question is, what i need to do, to populate my dropdown in order? I'm still in the beginner phase in java script and Jquery. Appreciate your help

Thanks

David
  • 53
  • 1
  • 1
  • 7
  • if you create a jsFiddle that shows the issue, it makes it easier to help :) Here's the link: http://jsfiddle.net/ – mtyson Jul 10 '14 at 20:10

3 Answers3

0

You could try this:

function dropdown(){
    var html = html + "<option value='All'>All</option>";
    var colValue = getColumn("COLUMN");
    colValue.sort();
    for( var i = 0; i < colValue.length; i++ ) {
        var valueRow = colValue[i];
        html = html + "<option value='" + valueRow.c + "'>" + valueRow.c + "-" + valueRow.v + "</option>";
    }
    $('#id').append(html);    

}
Alex Funk
  • 435
  • 1
  • 3
  • 11
0

Based on what you are saying, it looks like colValue looks like this:

colValue = [
  { c="A3", v="a3Value" },
  { c="A1", v="a2Value" } // etc.
]

So you will need to decide what property to sort on, and then you can create a comparator:

function createComparator(property) {
    return function(a, b) {
        return a[property] > b[property];
    };
}

You would use it like this:

colValue.sort(createComparator("c"));

Based on this SO answer: How to sort javascript objects based on their properties, specifying the property

Community
  • 1
  • 1
mtyson
  • 8,196
  • 16
  • 66
  • 106
0

Since valueRow is an object instead of an array and you want to sort on valueRow.v you need more than Array.sort().

Take a look at lodash's sortBy: http://lodash.com/docs#sortBy

_.sortBy(valueRow, 'c')

kcathode
  • 94
  • 3