Skip to content

How to group and sort a JS array

agershun edited this page Dec 28, 2014 · 1 revision

How to group and sort a JS array?

Source: StackOverflow.com

Question

There is an array of objects with two properties: Name and Hours.

For example:

    array = [
        {name: "ANDY", hours: 40 }, 
        {name: "ANDY", hours: 50 }, 
        {name: "GREG", hours: 40 },
    ];

For example I would like the result of the sorting to have the Andy with the most hours first, then Andy with slightly less hours, and then Greg because his name comes later alphabetically and so on and so on.

Answer

    var res = alasql('SELECT * FROM ? ORDER BY Name, Hours DESC',[array]);

Try this example at jsFiddle

Clone this wiki locally