Kyle
Kyle

Reputation: 67

Javascript - Group by one property, sort by another

I have an array of objects, and I currently have them sorted by one property (a number). I have a sort button that will allow a user to sort them by another attribute (a string). How can I sort them by a specific value, and keep them in the order of the number sort in javascript?

A quick example, using a person with a name, age, and favorite color:

Steve, 27, Blue
Joe, 28, Red
John, 30, Green
Jane, 33, Blue
Julie, 35, Blue
Kevin, 40, Red

So, if a user wanted to sort the list by people with the favorite color of Red, I'd want it to show like this:

Joe, 28, Red
Kevin, 40, Red
Steve, 27, Blue
Jane, 33, Blue
Julie, 35, Blue
John, 30, Green

The order of the property after the selected one doesn't matter, as long as they are grouped and sorted by age. For example, the above list (sorted by red) could have John listed after Kevin, so long as all Steve, Jane and Julie all stayed in the same order.

Basically, I want to group by a string, and then sort the group by a number.

Thank you for any help!

Upvotes: 1

Views: 1300

Answers (2)

Rudie
Rudie

Reputation: 53851

Sounds like you're trying to ORDER BY (color = Red), color, age (not SQL syntax): first Red, then grouped by color, then age per group.

That's tricky in 1 sorter...

I think this is the one:

function(a, b) {
    if (a.color == 'Red') {
        if (b.color == 'Red') {
            // Both Red, so check Age
            return a.age - b.age;
        }
        // A is Red, so to top
        return -1;
    }

    if (b.color == 'Red') {
        // B is red, so to top
        return 1;
    }

    if (a.color == b.color) {
        // Same color, so check Age
        return a.age - b.age;
    }

    // Different color, so check that
    return a.color < b.color ? -1 : 1;
}

Result seems like it:

Joe     28  Red
Kevin   40  Red
Steve   27  Blue
Jane    33  Blue
Julie   35  Blue
John    30  Green

Maybe it could've been shorter, but I can't think anymore.

Demo on http://jsfiddle.net/rudiedirkx/83sm2squ/

Upvotes: 0

xathien
xathien

Reputation: 822

Javascript's .sort() function takes a function as a parameter that can be used to do arbitrary sorts.

An example that would accomplish your desired sort:

people.sort(function(a, b) {
    if (a.color == 'Red' && b.color != 'Red') return 1;
    if (a.color != 'Red' && b.color == 'Red') return -1;
    return 0;
});

Upvotes: 1

Related Questions