1

Can someone help me with Array.sort()? I can do sorting on one value (e.g. return a < b) but not with more values. I need this case, when some primary values has the same result.

E.g. array:

var data =    [
        {
            "name": "Paolos Pizza", 
            "rating_count": 20,
            "rating_value": 5,
            "price": 7
        },

        {
            "name": "Bella Italia", 
            "rating_count": 55,
            "rating_value": 3,
            "price": 7
        },

        {
            "name": "Mama Mia", 
            "rating_count": 2,
            "rating_value": 5,
            "price": 99
        },

        {
            "name": "Mario's" ,
            "rating_count": 23,
            "rating_value": 6,
            "price": 7
        },

        {
            "name": "Colazione e Roma" ,
            "rating_count": 52,
            "rating_value": 4,
            "price": 7
        }

    ];

First I want to sort the Array descending on the key price. If some entries have the same price, than I want to sort it ascending depending on rating_value. If some entries have the same price and the same rating_value, than I want to sort ascending on rating_count.

How can I solve this?

Dineshaws
  • 1,991
  • 13
  • 24
tiefenb
  • 767
  • 1
  • 12
  • 26

2 Answers2

1

This is your solution:

arr.sort(function(a,b) {
    if(a.price != b.price) return a.price < b.price;
    if(a.rating_value != b.rating_value) return a.rating_value < b.rating_value;
    return a.rating_count < b.rating_count;
});

You can make sorting direction accordingly..

Aju John
  • 2,131
  • 1
  • 8
  • 21
1

You can chain the comparison parts with logical OR || and take the difference as result for the sort order callback.

var array = [{ "name": "Paolos Pizza", "rating_count": 20, "rating_value": 5, "price": 7 }, { "name": "Bella Italia", "rating_count": 55, "rating_value": 3, "price": 7 }, { "name": "Mama Mia", "rating_count": 2, "rating_value": 5, "price": 99 }, { "name": "Mario's", "rating_count": 23, "rating_value": 6, "price": 7 }, { "name": "Colazione e Roma", "rating_count": 52, "rating_value": 4, "price": 7 }];

array.sort(function (a, b) {
    return b.price - a.price ||
        a.rating_value - b.rating_value ||
        a.rating_count - b.rating_count;
});

document.write('<pre>' + JSON.stringify(array, 0, 4) + '</pre>');
Nina Scholz
  • 323,592
  • 20
  • 270
  • 324