var a = {prop: 3, name: 'a'}, b = {prop: 2, name: 'b'}, c = {prop: 1, name: 'c'}; var array = [ a, b, c ], result = null; result = array.sort(function(a, b){ var c = a.prop, d = b.prop; if( c < b ){ return -1; }else if( c > b ){ return 1; } return 0; }); for(var i in result){ console.log(result[i].name); // a, b, c } 

That doesn't work ...

Added by:
And in js so you can not sort? And what's the difference sort that move places?

  • A couple of days ago [a similar question] [1] was. Maybe you need it. [1]: hashcode.ru/questions/360498 - Deonis
  • @Deonis, thanks! I have the same thing as your link, only with an error :) But thanks to your help I could see it. - vas

3 answers 3

You have two errors:

  1. The sort method sorts the array in place, i.e. modifies the array to which it is applied. If you want to keep the original array, make a copy before sorting:

    result = array.slice (). sort ()

  2. You use b in comparisons (c < b) and (c > b) , although you would like d.

The corrected program works as it should.

    In principle, multidimensional sorts are solved by writing complex functions for sort (), but this is difficult, so you can use some library, for example, this function can be implemented using the Alasql library, which is designed to handle arrays as in SQL.

     var a = {prop: 3, name: 'a'}, b = {prop: 2, name: 'b'}, c = {prop: 1, name: 'c'}; var array = [ a, b, c ]; var result = alasql('SELECT * FROM ? ORDER BY name',[array]); 

    The order and number of fields can be varied using the keywords ASC (ascending) / DESC (descending), for example, like this:

     var result = alasql('SELECT * FROM ? ORDER BY name DESC, prop ASC',[array]); 

    Your jsFiddle example.

    • one
      @agershun, your library is interesting, but connecting more than 200 Kb for sorting is somehow too much :) - Deonis
      var a = {prop: 3, name: 'a'}, b = {prop: 2, name: 'b'}, c = {prop: 1, name: 'c'}, array = [ a, b, c ]; for (var i=0; i < array.sort(function(obj1, obj2){ return obj1.prop-obj2.prop; }).length; i++) { console.log(array[i].prop); }