dude
dude

Reputation: 4962

Sorting values in ascending and descending using jquery

$1 = 10;
$2 = 30;
$3 = 5;

$("#bidtmp").val('');

if ($1 > $2) {
    $("#bidtmp").val('1');
} else if ($2 > $3) {
    $("#bidtmp").val('2');
} else if ($3 > $1) {
    $("#bidtmp").val('3');
} else if ($1 > $3) {
    $("#bidtmp").val('1');
} else if ($2 > $1) {
    $("#bidtmp").val('2');
} else if ($3 > $2) {
    $("#bidtmp").val('3');
}

how to sort values in ascending order using jquery? Above is the code what i have tried?

Upvotes: 3

Views: 22055

Answers (3)

brandonscript
brandonscript

Reputation: 72875

This is way super complicated ;)

Try this instead:

var arr = [$1, $2, $3]
arr.sort() // asc
arr.sort().reverse() // desc

Upvotes: 4

thecodeparadox
thecodeparadox

Reputation: 87073

You can try:

$("#bidtmp").val( Math.max($1, $2, $3) );

From your code it seem you're trying to set max value to #bidtmp and for that above will work.

But for sorting try sort() method like below:

[$1, $2, $3].sort(function(a, b) {
  return a-b;
});

for descending return b-a;.

Upvotes: 5

Flops
Flops

Reputation: 1420

var $1 = 10, $2 = 30, $3 = 20;
var sorted_arr = [$1, $2, $3].sort();

Do not forget to declare vars.

Sort method can get a function as argument for custom sort.

Upvotes: 0

Related Questions