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