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

Questions:

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:

[{"id":"ABC","num":111},
{"id":"DEF","num":130},
{"id":"XYZ","num":115},
{"id":"QRS","num":98},
{"id":"DEF","num":119},
{"id":"ABC","num":137},
{"id":"LMN","num":122},
{"id":"ABC","num":108}]

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:

[{"id":"QRS","num":98},
{"id":"ABC","num":108},
{"id":"ABC","num":111},
{"id":"ABC","num":137},
{"id":"XYZ","num":115},
{"id":"DEF","num":119},
{"id":"DEF","num":130},
{"id":"LMN","num":122}]

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;
});
Answers: