Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

custom sort method in jquery/javascript

I want to sort a Array in custom way

Given arary:

arry = [0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,14,14,15,15,16,16,17,17,18,18,21,21,22,22,23,23]

Expected output:

[21,22,22,23,23,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,14,14,15,15,16,16,17,17,18]
like image 695
Gagan Avatar asked Sep 22 '26 07:09

Gagan


1 Answers

You could check the value first and the sort number greater than 20 first.

var array = [0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15, 16, 16, 17, 17, 18, 18, 21, 21, 22, 22, 23, 23],
    predicate = function (v) { return v > 20; };

array.sort(function(a, b) {
    return predicate(b) - predicate(a) || a - b;
});

console.log(array);
like image 105
Nina Scholz Avatar answered Sep 24 '26 19:09

Nina Scholz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!