Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Find max number based on two fields in an array

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}]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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 );
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading