Galymzhan Aigelov
Galymzhan Aigelov

Reputation: 3

How to sort array of objects in jQuery

I have an array in this way

{
    1="Металлургия и производство готовых металлических продуктов",
    2="Химическая промышленность",
    3="Альтернативная энергетика",
    4="Транспортная инфраструктура"
}

I've looked another questions like this, but couldn't find anything.

Full code:

$.getJSON('/project/'+ clicked +'s/', function(data) {

            var info =
                '<td></td>'
                +'<td>'
                    +'<select name="'+ clicked +'_id'+ id +'" id="edit_'+ clicked +'_id'+ id +'">'
                        +'<option value="">'+obj['list_'+lang]+'</option>';

                        for (var i in data) {
                                info += '<option value="'+ i +'">'+ data[i] +'</option>';
                        }
                    info += '</select>'
                +'</td>';

            $('#'+ clicked +'s'+ id).show().html(info);

        });

In data I have an array which is above. I want to sort them alphabetically like this: 3="Альтернативная энергетика" 1="Металлургия и производство готовых металлических продуктов"

class Controller_Project extends Controller_Website {
public function action_sectors() {
    $sectors = ORM::factory('sector')
        ->find_all()
        ->as_array('id', 'name');

    $ar_sectors = array();
    switch ($this->user_language) {
        case 'ru':
            $ar_sectors[15] = 'Агропромышленный комплекс';
            $ar_sectors[3] = 'Альтернативная энергетика';
            $ar_sectors[7] = 'АПК и текстильная промышленность';
            $ar_sectors[13] = 'Атомная промышленность и атомная энергетика';
            break;
        case 'en':
            $ar_sectors[15] = 'Agricultural Sector';
            $ar_sectors[3] = 'Alternative Energy Industry';
            $ar_sectors[7] = 'Agriculture and textiles';
            $ar_sectors[13] = 'Atomic Industry';
            break;
    }

    $sectors = $ar_sectors;
    $this->auto_render = FALSE;
    $this->request->response = json_encode($sectors);

}

}

The site where code is situated http://new.baseinvest.kz/project

Upvotes: 0

Views: 4015

Answers (1)

George Reith
George Reith

Reputation: 13476

You can use JavaScript's native sort method and pass your own comparative function, depending on how you wish to sort them: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

e.g. To sort by a property of each object alphabetically

var arr = [{say: "hi"}, {say: "bye"}];

arr.sort(function(a, b) {
   if (a.say > b.say) {
      return 1;
   }
   if (a.say < b.say) {
      return -1;
   }
   return 0;
});

// arr now equals [{say: "bye"}, {say: "hi"}];

Working example: http://jsfiddle.net/uKAEz/

Edit: In response to your updates it is clear you are not sorting an array of objects but are sorting an array of strings. It also appears they are in Russian. The following should do what you want:

arr.sort(function(a, b) {
    return a.localeCompare(b, "ru");
});

See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare for information on localCompare which facilitates sorting unicode strings.

Upvotes: 1

Related Questions