Home » Javascript » Sort array of objects, then group by id (JavaScript)

Sort array of objects, then group by id (JavaScript)

Posted by: admin August 19, 2018 Leave a comment


I have an array of objects that requires some unconventional sorting. Each object contains an id string and a num int. Some unsorted dummy data:


I need to sort ascending by num – BUT, if an id appears more than once, additional records for that id should “float up” in position to reside below its sibling with the next smallest num.

The end result would be:


The actual array could contain 15k+ records, so any efficient solutions would be greatly appreciated. A .sort(function(a,b) {...}) with some nested “ifs” works fine to get a basic sort in place, but I’m stumped on the “float up” logic. Thanks in advance.

EDIT: what I have so far (basic nested sort):

const sortedData = origData.sort(function(a, b) {
  if (a.num === b.num) {
    if (a.id === b.id) {
      return a.id.localeCompare(b.id);
  return a.num - b.num;