This article describes the usage of array sort and reverse in Javascript. Share it for your reference. The specific analysis is as follows:
The sort() method is used to sort elements of an array.
reverse() reverse() reverses the elements in the array inversely order
First let's try the following code:
The code copy is as follows: var values = [1, 0, 5, 15, 10];
values.reverse();
console.log(values);
What will the output result be:
[ 10, 15, 5, 0, 1 ]
reverse() is just a simple way to reverse the array, so what I want to complain about next is sort()
The code copy is as follows: var values = [1, 0, 5, 15, 10];
values.sort();
console.log(values);
The output result of this function is:
[ 0, 1, 10, 15, 5 ]
What's going on?
In fact, toString() will be used inside the sort() function, and the String comparison is through ASCII. Therefore, if we need to sort it, it is better to write a sort() yourself.
The code copy is as follows: var values = [1, 0, 5, 15, 10];
function compare(value1, value2) {
if (value1 < value2) {
return -1;
} else if (value1 > value2) {
return 1;
} else {
return 0;
}
}
values.sort(compare);
console.log(values);
If you change -1 and 1, you can sort in reverse.
The output result is now:
[ 0, 1, 5, 10, 15 ]
A simpler way to write it is to use return value2 - value1 inside compare();
I hope this article will be helpful to everyone's JavaScript programming.