-4

Suppose we have an array

[{no:1,count:1},{no:2,count:1},{no:2,count:2},{no:3,count:1},{no:4,count:1},{no:5,count:1}]

So I would like to find the top 5 no in this array but if two numbers are equal then the one with the higher count should be selected for example in the above case the top 5 should be

[{no:5,count:1},{no:4,count:1},{no:3,count:1},{no:2,count:2},{no:1,count:1}]

2 Answers2

0

It's easy enough to write your own comparison function:

function compare( a, b ) {
  if ( a.no < b.no ){
    return 1;
  }
  if ( a.no > b.no ){
    return -1;
  }

  if( a.no === b.no) {
    if ( a.count < b.count ){
      return 1;
    }
    if ( a.count > b.count ){
      return -1;
    }
  }
  return 0;
}

const data = [
  {no:1,count:1},
  {no:2,count:1},
  {no:2,count:2},
  {no:3,count:1 },
  {no:4,count:1},
  {no:5,count:1}
];
data.sort( compare );
MrFabio_25
  • 478
  • 5
  • 9
0

Anoter one sort approach with an object:

const data = [{no:1,count:1},{no:2,count:1},{no:2,count:2},{no:3,count:1},{no:4,count:1},{no:5,count:1}];

const getTop = (arr, size = 5) => Object.values(
  arr.reduce((acc, e) => {
    acc[e.no] ??= e;
    if (acc[e.no].count < e.count) acc[e.no] = e;
    return acc;
  }, {})
)
.reverse()
.slice(0, size);

console.log(getTop(data, 5));
.as-console-wrapper { max-height: 100% !important; top: 0 }
A1exandr Belan
  • 4,442
  • 3
  • 26
  • 48