JavaScript numeric array sorting sample share

  • 2020-03-30 03:06:30
  • OfStack

However, we can see the problem when we use it. The array sort method here does not sort according to the size of the number we imagined, but changes the original data according to the string test result. That's not what we want.

So how do we get what we want in order of the size of the Numbers that we're thinking about. We can write a function to implement it ourselves.



var values = [0, 1, 5, 10, 15];
//Asc ascending function
function compareAsc(value1, value2) {
    if (value1 > value2) {
        return 1;
    } else if (value1 < value2) {
        return -1;
    } else {
        return 0;
    }
}
//Desc descending function
function compareDesc(value1, value2) {
    if (value1 > value2) {
        return -1;
    } else if (value1 < value2) {
        return 1;
    } else {
        return 0;
    }
}
values.sort(compareAsc);
console.log(values);  // [0, 1, 5, 10, 15]
values.sort(compareDesc);
console.log(values);  // [15, 10, 5, 1, 0]


Related articles: