0

I have an array of objects with the following type:

{
 foo: number;
 bar: number;
 rankFoo?: number;
 rankBar?: number;
}

The naive approach would be to sort the objects by each property, then loop over the array and rank each object by index:

// sort by foo
arr.sort((a, b) => a.foo > b.foo ? -1 : a.foo === b.foo ? 0 ? 1)

// rank by foo
for(let i = 0; i < arr.length; i++){
 arr[i].rankFoo = i;
}

// repeat the same process for bar...

I'm looking for an algorithm with less complexity than this approach.

  • Can you multiply each by an ordinal value and use this as the sort? Largest ordinal is the first to sort, obviously. e.g. rankFoo * 1000 + rankBar * 100 + foo * 10 + bar (as an example). Obviously you can write in the checks for null values. – Paul Aug 14 '22 at 13:21
  • I don't see a much simpler approach, but you could sort the foos, assign them each an index, and then loop through the objects, assigning each to the value you assigned to their foo – Barry Carter Aug 14 '22 at 13:27
  • I think you need to provide more information as to why and set some kind of stipulation as to what is inside/outside the box. – Paul Aug 14 '22 at 13:29
  • I would ask myself the question if this is the right approach. The Array is sorted and knows about the positions of the objects. Why the objects need to know about this themselves? Clearly you need 2 arrays each sorted on their own property. Also what if you insert an object in the array, all ranking properties are of.... – Aldert Aug 14 '22 at 13:29
  • Once again, use this super function https://stackoverflow.com/a/22672370/3807365 to sort array of objects by property and sub property and so on. – IT goldman Aug 14 '22 at 14:20

0 Answers0