Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grouped sorting on a JS array

Tags:

javascript

I have 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 in my array 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.

Since the array.sort() function passes two elements of the array to compare i realise this is not the way to go for me but fail to come up with an elegant solution. Please help me out.

like image 478
Rafał Saltarski Avatar asked Apr 23 '13 08:04

Rafał Saltarski


People also ask

How do you group an array in JavaScript?

The group() method groups the elements of the calling array according to the string values returned by a provided testing function. The returned object has separate properties for each group, containing arrays with the elements in the group. This method should be used when group names can be represented by strings.

How do you sort an array of objects in JavaScript?

To sort an array of objects in JavaScript, use the sort() method with a compare function. A compare function helps us to write our logic in the sorting of the array of objects. They allow us to sort arrays of objects by strings, integers, dates, or any other custom property.

Can we sort elements in array?

The sort() method sorts the elements of an array in place and returns the reference to the same array, now sorted.


1 Answers

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

function cmp(x, y) {
  return x > y ? 1 : (x < y ? -1 : 0);
}


array.sort(function(a, b) {
  return cmp(a.name, b.name) || cmp(b.hours, a.hours)
})

console.log(array)

If javascript had a spaceship operator that would be even more elegant. Note that this code is easy to extend to use more properties:

ary.sort(function(a, b) {
    return cmp(a.name, b.name) || cmp(a.age, b.age) || cmp(b.hours, a.hours) || ....
})
like image 100
georg Avatar answered Sep 21 '22 03:09

georg